[英]Java Trying to do reflection(class instance and invoke method at runtime)
這是我的代碼。
String name = "expevaluator." + super.left.getClass().getSimpleName() + super.right.getClass().getSimpleName() + "Addition";
try {
Object instance;
instance = Class.forName(name).newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger(Addition.class.getName()).log(Level.SEVERE, null, ex);
}
我正在嘗試調用變量“name”類的evaluate函數。
這是評估功能。
public Number evaluate(int left, int right) {
return left + right;
}
這是IntegerIntegerAddition類的evaluate方法
我還有IntegerDoubleAddition類的evaluate方法
public Number evaluate(int left, double right) {
return left + right;
}
所以變量名可以有“IntegerIntegerAddition”或“IntegerDoubleAddition”,我希望它們都使用2個參數調用Evaluate方法。
您將需要使用實際方法所需的名稱和參數類型創建Method對象。 然后,您希望使用對具有該方法的對象的引用,並在其上調用您的Method引用。
//These are all the types that my example references will use.
Object obj; //The instance that my method is going to be invoked on.
Object[] params; //The parameters for my method
String nameOfMethod; //The name of my method.
Class<?>[] paramTypes; //The types, in order, that my method accepts as parameters
Method m = obj.getClass().getMethod(nameOfMethod, paramTypes); //Create my Method object
m.invoke(obj, params); //Invoke that method!
getMethod()接受數組paramTypes的vararg。 因此,您可以直接在其中列出您的類型作為單獨的參數。 與Method.invoke()相同的是它的params參數。
m.invoke(obj, param1, param2, param3) //etc
你可以這樣做:
Method evaluate = instance.getClass().getDeclaredMethod( "evaluate", int.class, int.class );
evaluate.invoke( instance, 3, 1 );
這應該通過參數類型找到確切的方法(或者使用“int.class,long.class”作為第二種方法)並調用它,這里使用示例參數3和1.記住捕獲可能的異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.