Suppose I have an application that given a well known package name and class, I need to load that class reflectively and invoke some methods from it. Let's say this class is available in another java jar (the "library").
So far, before java 9, since all the classes in the classpath were available, it was straightforward to achieve this.
However, with Java 9, if the application "module" does not require the "library" package, the library class is not accessible.
How can I achieve the same behavior using modularized jars?
Example:
This is my application:
// This is defined in ReflectionApp.jar
// ReflectionApp
// └── src
// ├── module-info.java
// └── org
// └── reflection
// └── app
// └── ReflectionApp.java
//
package org.reflection.app;
import java.lang.reflect.Method;
public class ReflectionApp {
private static final String PACKAGE = "org.reflection.lib";
private static final String CLASS = "ReflectiveClass";
private static final String METHOD = "doSomeWork";
public static void main(String[] args) throws Exception {
// This will not work using java9
Class<?> klass = Class.forName(String.format("%s.%s", PACKAGE, CLASS));
Object obj = klass.getDeclaredConstructor().newInstance();
Method meth = klass.getDeclaredMethod(METHOD);
meth.invoke(obj);
}
}
And this is my library
// This is defined in ReflectionLib.jar
// ReflectionLib
// └── src
// ├── module-info.java
// └── org
// └── reflection
// └── lib
// └── ReflectiveClass.java
//
package org.reflection.lib;
public class ReflectiveClass {
public void doSomeWork() {
System.out.println("::: Doing some work!");
}
}
Aucun commentaire:
Enregistrer un commentaire