2017-10-21 52 views
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()的值,並訪問其數據?

+0

也使用反射。但你爲什麼這樣做?爲什麼你的類路徑中沒有jar文件?你想在更高的層面上實現什麼? –

+0

因爲'jarFile'可以動態更改。但是設置類路徑是一種靜態方式。 – QueN

回答

0

使用接口來限制返回值。

如果返回值沒有限制,則對其進行操作意味着您完全瞭解它。那麼你的'動態加載'的含義是什麼?

摘要正常的接口SomeInterface,然後

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

其他代碼只對SomeInterface工作,但並不需要知道什麼實際是。這是界面的力量。