实体类的私有方法,类外不能调用
/**
* @author pqYang
* @Date 20:39 2019/6/21
**/
public class SelfMethod {
private Strings;
private String getII(){
return "1+2=3";
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
反射的方法类
public class BaseTest {
/*
* @Param obj 实体类 * @Param methodName 方法名 * @Param retType 返回值类型 * @Param args 参数(无参数是不用写)
* @Author pqYang
* @Date 20:50 2019/6/21
* @return T
**/
@SuppressWarnings({"unchecked","rawtypes"})
public T invokeHiddenMethod(Object obj, String methodName, Class retType, Object... args) {
try {
Class[] types =new Class[args.length];
for (int i =0; i < types.length; i++) {
types[i] = args[i].getClass();
}
Method declaredMethod = obj.getClass().getDeclaredMethod(methodName, types);
declaredMethod.setAccessible(true);
return (T) declaredMethod.invoke(obj, args);
}catch (NoSuchMethodException e) {
e.printStackTrace();
}catch (IllegalAccessException e) {
e.printStackTrace();
}catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
测试的类
public class TTTT {
/*
* @Param
* @Author pqYang
* @Date 20:50 2019/6/21
* @return void
**/
@Test
public void mainsss() {
SelfMethod selfMethod =new SelfMethod();
BaseTest baseTest =new BaseTest();
String getII = baseTest.invokeHiddenMethod(selfMethod,"getII", String.class);
System.out.println(getII);
}
}
网友评论