从JAR文件中的类中获取值

问题描述:

我想在JAR中运行方法,并且该方法看起来像public static SomeType getValue()从JAR文件中的类中获取值

我尝试使用反射,它似乎好:

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"); 

但是,同时得到一个返回值是这样的:

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

value的类型不能为targetType,不是吗?然而,类型SomeType是在JAR文件中,所以我不能这样做SomeType value = ~~

然后,我怎样才能得到getValue()的值,并访问其数据?

+0

也使用反射。但你为什么这样做?为什么你的类路径中没有jar文件?你想在更高的层面上实现什么? –

+0

因为'jarFile'可以动态更改。但是设置类路径是一种静态方式。 – QueN

使用接口来限制返回值。

如果返回值没有限制,则对其进行操作意味着您完全了解它。那么你的'动态加载'的含义是什么?

摘要正常的接口SomeInterface,然后

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

其他代码只对SomeInterface工作,但并不需要知道什么实际是。这是界面的力量。