如果方法接受非原始数据类型,则可以使用以下方法来调用任何类的私有方法:public static Object genericInvokeMethod(Object obj, String methodName,
Object... params) {
int paramCount = params.length;
Method method;
Object requiredObj = null;
Class>[] classArray = new Class>[paramCount];
for (int i = 0; i
classArray[i] = params[i].getClass();
}
try {
method = obj.getClass().getDeclaredMethod(methodName, classArray);
method.setAccessible(true);
requiredObj = method.invoke(obj, params);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return requiredObj;
}
接受的参数是obj,methodName和参数。例如public class Test {private String concatString(String a, String b) {
return (a+b);}}
方法concatString可以作为调用Test t = new Test();
String str = (String) genericInvokeMethod(t, "concatString", "Hello", "Mr.x");