//测试私有方法
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
//测试私有变量
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
翻译一下
Method method = targetClass.getDeclaredMethod("方法名", 方法参数类型);
method.setAccessible(true);
return method.invoke(类的实例, 方法参数值);
Field field = targetClass.getDeclaredField("私有变量名");
field.setAccessible(true);
field.set(类的实例, 私有变量值);
------------------------------------------------------------------------------------
实例
class NumParser(){
//私有变量
private Query query_;
public NumParser(Query query){
//构造函数
query_ = query
}
private void fun(){
//私有方法
}
}
NumParser numParser = new NumParser(query)
Method method = numParser.getClass().getDeclaredMethod("fun", null);
method.setAccessible(true);
method.invoke(numParser, null);
Field field = numParser.getClass().getDeclaredField("query_");
field.setAccessible(true);
Object after = field.get(numParser);
//多种参数的写法***********************************************************************
Method method = numParser.getClass().getDeclaredMethod("fun", new Class[]{int.class,int.class});
Object result = method.invoke(cal, new Object[]{1,10});