Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to loading a class with Class.forName()?

In my library's code, I load class names from an XML file using JAXB, in order to instanciate them later on using Class.forName(). A fictive example to illustrate the case:

public void libraryMethod() throws Exception {
  List<String> classNames = loadClassNamesFromXML();

  for (String className : classNames) {
    Class.forName(className).newInstance().doThings();
  }
}

Now, some users use OSGi to configure their applications, and they load my library with a different class loader than the classes they configure using my XML structure. This means that loading may fail, as the class cannot be found.

Is there any more reliable way to load such classes? Or is there any other way to configure these instances? I'm open to suggestions that result in this:

public void libraryMethod() throws Exception {
  // Spring does things like this:
  List<SomeType> instances = loadInstancesFromXML();

  for (SomeType instance : instances) {
    instance.doThings();
  }
}

Some constraints:

  • From a library perspective, the lifecycle of those instances is unimportant. If they have (user) state, my library would not notice.
  • I want to keep things simple in this library, so I want to avoid creating external dependencies on configuration frameworks like spring, for instance. So I'm only interested in solutions that can be achieved with standard JDK 6+ distributions.
  • I would really like to keep my simple XML configuration file (slight adaptations to the XML structure are OK).
like image 662
Lukas Eder Avatar asked Feb 19 '23 20:02

Lukas Eder


1 Answers

If you want your library to be flexible and work in both OSGi and non-OSGi environment, you should allow users provide their own ClassLoader's or let them tell your library which class names they have. Read Neil Bartlett blog post.

Original link returns a 404. You can access the article on the Wayback Machine.

like image 171
Ivan Dubrov Avatar answered Feb 26 '23 11:02

Ivan Dubrov