package com.tain_8_23_01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
/*
* 通过反射获取成员变量
* Class.getField(String) 方法可以获取类中的指定字段(可见的)
* 如果私有的可以用getDeclaedField("name")方法获取,通过set(obj,"XX")方法可以设定指定对象上该字段的值
* 如果是私有的需要先调用setAccessible(true)设置访问权限,用获取的指定字段调用get(obj)可以获取指定对象中该字段的值
*
*/
public class Demo2_Field {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.tain_8_23_01.Person");
Constructor c = clazz.getConstructor(String.class,int.class); //获取有参的构造
Person p = (Person) c.newInstance("孙悟空",500); //通过有参构造创建对象并赋值
//
// //NoSuchFieldException 私有成员不允许这样访问
// Field f = clazz.getField("name"); //获取姓名字段
// f.set(p, "嬴政"); //修改名字
Field f1 = clazz.getDeclaredField("name"); //暴力反射获取字段
Field f2 = clazz.getDeclaredField("age");
f1.setAccessible(true); //去除私有权限
f2.setAccessible(true);
f1.set(p, "嬴政");
f2.setInt(p, 2000);
System.out.println(p);
}
}
package com.tain_8_23_01;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
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;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
通过反射获取成员变量
最新推荐文章于 2023-11-29 23:31:20 发布