从 JAR 文件中的 class 获取值
Getting a value from the class in a JAR file
我想 运行 JAR 中的一个方法,该方法看起来像 public static SomeType getValue()
。
我试过用反射,好像没问题:
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");
但是在获得这样的 return 值时:
targetType value = targetClass.cast(getValueMethod.invoke(null));
value
的类型不能是targetType
,对吗?但是,类型 SomeType
在 JAR 文件中,所以我不能像 SomeType value = ~~
那么,如何正确获取getValue()
的值并访问它的数据呢?
使用接口限制 return 值。
如果return值没有限制,你对它进行操作就意味着你对它了如指掌。那么你的'dynamic loaded'是什么意思?
抽象一个普通接口SomeInterface
,然后
SomeInterface value = targetClass.cast(getValueMethod.invoke(null));
其他代码仅适用于 SomeInterface
但不需要知道实际情况。这是界面的力量。
我想 运行 JAR 中的一个方法,该方法看起来像 public static SomeType getValue()
。
我试过用反射,好像没问题:
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");
但是在获得这样的 return 值时:
targetType value = targetClass.cast(getValueMethod.invoke(null));
value
的类型不能是targetType
,对吗?但是,类型 SomeType
在 JAR 文件中,所以我不能像 SomeType value = ~~
那么,如何正确获取getValue()
的值并访问它的数据呢?
使用接口限制 return 值。
如果return值没有限制,你对它进行操作就意味着你对它了如指掌。那么你的'dynamic loaded'是什么意思?
抽象一个普通接口SomeInterface
,然后
SomeInterface value = targetClass.cast(getValueMethod.invoke(null));
其他代码仅适用于 SomeInterface
但不需要知道实际情况。这是界面的力量。