0
我已經爲Java反射創建了一個Utility類。如果方法名稱作爲參數傳遞 ,那麼我的意圖是什麼,那麼它應該返回Collecton的值。該實用程序類是在Eclipse插件項目(com.abc.utility
)中創建的。 我將這個工具類添加到另一個插件項目(com.abc.dao
)。現在當我調用這個實用程序方法時,我得到了ClassNotFoundException
。 我明白了這個問題。我不想將依賴項添加到com.abc.utility
項目中。而不是 com.abc.utility
插件項目應該添加爲其他項目的依賴項。classnotfound異常反射
我不知道如何解決。你能幫我解決這個問題嗎?
@SuppressWarnings({ "unchecked", "rawtypes" })
public <K>Collection<K> getCollection(T t, String methodName) {
Method[] methods =t.getClass().getMethods();
for (Method method : methods) {
String name = method.getName();
if (name.equals(methodName)) {
String name2 = method.getReturnType().getName();
Object newInstance = null;
try {
newInstance = Class.forName(name2).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e1) {
e1.printStackTrace();
}
if (newInstance instanceof Collection) {
try {
return (Collection)method.invoke(t, null);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return Collections.emptyList();
}