import java.lang.reflect.Field;
class Persion{
public static String name="张三";
private int age = 32;
protected String idno = "112233445566";
public Persion(){
}
public Persion(String name){
this.name = name;
}
public Persion(String name,int age,String idno){
this.name = name;
this.age = age;
this.idno = idno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getIdno() {
return idno;
}
public void setIdno(String idno) {
this.idno = idno;
}
}
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException{
/* 获得类对象的三种方式*/
//1. 创建Persion对象 和persion对象
//注意二者是有区别的 persion对象存在于堆区 而persion对象存在方法区其实就是Persion类中的成员变量、结构体、方法属性
Persion persion = new Persion();
Class persion1 = persion.getClass();
// hashcode 返回对象存储的物理地址(哈希码值)
System.out.println(persion1.hashCode());
System.out.println("persion1 = " + persion1.getName());
System.out.println("----------persion2-------------");
//2. 每一个类都有一个静态的class成员变量,不用创建可以直接赋值
Class persion2 = Persion.class;
System.out.println(persion2.hashCode());
//已经把Persion对象赋值给persion2 为何persion2无法引用静态变量呢?????
//System.out.println(persion2.name);
System.out.println(Persion.name); //类可以直接引用静态变量
//创建类的实例对象 通过创建实例获取对象的属性
Object obj = persion2.newInstance();
Field field =persion2.getField("name");
Object obj2 = field.get(obj);
System.out.println(obj2.toString());
System.out.println("persion2 = " + persion2.getName());
System.out.println("----------persion3-------------");
//3. 反射获取
Class persion3 = Class.forName("com.lsw.forname.Persion");
Object obj3 = persion3.newInstance();
System.out.println(persion3.hashCode());
System.out.println("persion3 = " + persion3.getName());
//获取所有的成员变量
/*Field[] fields = persion3.getDeclaredFields();
for(Field str:fields)
System.out.println(str + "|getName="+str.getName()+ "|value="+str.get(str.getName()));*/
//Exception in thread "main" java.lang.IllegalAccessException:
//Class com.lsw.forname.Test can not access a member of class
//com.lsw.forname.Persion with modifiers "private"
//反射的定义如下:AVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;
//这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
//但是报错了 查找原因
field = persion3.getDeclaredField("age");
field.setAccessible(true); //解除私有变量属性
field.set(obj3, 32);
System.out.println(field.getName() + "=" + field.get(obj3));
/**
2134502363
persion1 = com.lsw.forname.Persion
----------persion2-------------
2134502363
张三
张三
persion2 = com.lsw.forname.Persion
----------persion3-------------
2134502363
persion3 = com.lsw.forname.Persion
age=32
*/
}
}