Search code examples
javareflectionclassloader

Getting a value from the class in a JAR file


I want to run a method in JAR, and the method will look like public static SomeType getValue().

I tried to use reflection and it seemed okay:

URLClassLoader classLoader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, Main.class.getClassLoader());
Class targetClass = classLoader.loadClass("some.package.TargetClass");
Class targetType = classLoader.loadClass("some.package.SomeType");
Method getValueMethod = targetClass.getMethod("getValue");

But while getting a return value like this:

targetType value = targetClass.cast(getValueMethod.invoke(null));

value's type cannot be targetType, isn't it? However, the type SomeType is in the JAR file, so I can't do like SomeType value = ~~

Then, how can I get getValue()'s value properly and access its data?


Solution

  • Use interface to restrict the return value.

    If the return value has no limit, you operate on it means you know all about it. So what's the meaning of your 'dynamic loaded'?

    Abstract a normal interface SomeInterface, and then

    SomeInterface value = targetClass.cast(getValueMethod.invoke(null));
    

    Other code only work for SomeInterface but don't need to know what actual it is. It's the interface's power be.