利用反射调用私有方法、访问私有属性
利用反射,首先是Class对象的获取,之后是Method和Field对象的获取。
以Method为例,从文档中可以看到:
getMethod()方法返回的是public的Method对象,
而getDeclaredMethod()返回的Method对象可以是非public的。
Field的方法同理。
访问私有属性和方法,在使用前要通过AccessibleObject类(Constructor、 Field和Method类的基类)中的setAccessible()方法来抑制Java访问权限的检查。
package com.hj.refelsh;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RefleshTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class clazz = Class.forName("com.hj.refelsh.GotoTest");
GotoTest gotoTest = null;
Object object = clazz.newInstance();
if (object instanceof GotoTest) {
gotoTest = (GotoTest) object;
// Method methods[] = clazz.getMethods();
Method methods[] = clazz.getDeclaredMethods();
for (Method _method : methods) {
System.out.println("#########################");
_method.setAccessible(true);
System.out.println(_method.getName());
if ("testGoto".equals(_method.getName())) {
Object returnObj = _method.invoke(gotoTest, "我的天");
Object claObj = returnObj.getClass();
System.out.println("return obj:>>"+claObj+" %%%%% return msg:>>"+returnObj);
System.out.println(_method);
}
System.out.println("#########################");
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.hj.refelsh;
import com.hj.refelsh.interfaces.FMethod;
public class GotoTest implements FMethod{
private String name;
private Integer age;
public GotoTest(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public GotoTest() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
private String testGoto(String str) {
return "i am method by reflesh:>>"+str;
}
@Override
public void prints() {
// TODO Auto-generated method stub
System.out.println("fack you");
}
}
package com.hj.refelsh.interfaces;
public interface FMethod {
public void prints();
}
java反射技术访问私有方法
最新推荐文章于 2023-10-28 18:57:17 发布