-2

Thanks for helping me out

Today I have a very simple problem

Problem:

On my application startup, I am loading all the classes inside one package using

Class.forName("org.codehaus.jackson.JsonGenerator$Feature");
............................
............................ and so on

Like this I loaded all the classes, everything is fine, until I upgrade the Jar, so the Jar package is updated to some other package name, from org.codehaus.jackson to com.fasterxml.jackson. So I have to change class.forName code.

Solution required: Is the following code is possible

Class.forName("com.fasterxml.jackson.*");

or there is any other way to load all the classes under one package?

please help :)

Dupinder Singh
  • 7,175
  • 6
  • 37
  • 61
  • 3
    Putting these classes on the classpath isn't enough for you? This sounds really weird to me. – maio290 Mar 14 '20 at 05:39
  • Yes I can add, this facility is available I know that I just want to know is there any other feasibility or not . – Dupinder Singh Mar 14 '20 at 05:43
  • 1
    Your code above accomplishes exactly nothing useful, unless you have unused classes with static initializers or some other strange architecture. Unclear what you're asking. – user207421 Mar 14 '20 at 06:18
  • 1
    Your problem stems from code duplication and can be solved with the usual approaches: `String pkg = "org.codehaus.jackson."; Class.forName(pkg+"JsonGenerator"); Class.forName(pkg+"JsonGenerator$Feature"); Class.forName(pkg+ ..and..so..on..);` Then, there's a single place where you have to change `"org.codehaus.jackson."` to `"com.fasterxml.jackson."`. This does not affect what others said, such preloading should not be needed. – Holger Mar 20 '20 at 11:34

1 Answers1

-1

The Class.forName("com.fasterxml.jackson.*"); is not possible,
docs are very clear about it, that the name parameter should be:

name - fully qualified name of the desired class

In addition the Class.forName returns a single object representing a class behind given name.

Your question has that, if you upgrade/update jar file the packages of jackson can be one of org.codehaus.jackson or com.fasterxml.jackson. This is weird if you want to load the jackson classes dynamically and you are not sure what will be the base package for those classes.

But anyway, a kind of solution would be to scan with Reflections if the given package name contains required classes (or at least few of them, so you would know that the package is visible) like here:
Can you find all classes in a package using reflection?
And later loop through the package with classes to initialize them with Class.forName.

itwasntme
  • 1,442
  • 4
  • 21
  • 28
  • This doesn't make any more sense than the question. Reflection can't see a class that hadn't been loaded yet, and if it has been loaded already there is nothing else that needs doing. – user207421 Mar 14 '20 at 07:19