定义一个测试类
public class User {
private String name = "ppp";
private String sex;
private int age;
private void eat(String num){
System.out.println("我在"+this.name+"sadasd"+num);
}
public void drink(String witer){
System.out.println("我正在喝"+witer);
}
public void setAge(int age) {
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
}
使用反射使能访问私有属性
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class FanShe {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获取类对象
Class user = Class.forName("Demo01_static.User");
//获取实例
// User o =(User)user.newInstance();
User o = new User();
//获取类中的方法
Method eat = user.getDeclaredMethod("eat",String.class);
//获取类中的属性
Field name = user.getDeclaredField("name");
//设置私有属性使其可以更改
name.setAccessible(true);
System.out.println(name.get(o));
name.set(o,"kkkk");
System.out.println(name.get(o));
//设置私有方法使其可以修改
eat.setAccessible(true);
eat.invoke(o,"16");
}
}
标签:反射,Java,String,私有,void,sex,User,public,name
From: https://www.cnblogs.com/java-six/p/16813336.html