1
我想在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()
的值,並訪問其數據?
也使用反射。但你爲什麼這樣做?爲什麼你的類路徑中沒有jar文件?你想在更高的層面上實現什麼? –
因爲'jarFile'可以動態更改。但是設置類路徑是一種靜態方式。 – QueN