package com.field;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.work.Student;
public class FieldDemo {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
//创建Class类的对象
Class<Student> c = Student.class;
Student student = c.newInstance();
student.setName("张三");
student.setAge(19);
student.setSex('男');
System.out.println(student.toString());
System.out.println("-------------------------------------");
//创建Field数组,获得对象的所有属性
Field fields[]=c.getDeclaredFields();
//输出属性的类型,名称
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
String type=fields[i].getGenericType().toString();
String name=fields[i].getName();
Object value=fields[i].get(student);
System.out.println(type+"---"+name+"---"+value);
fields[i].setAccessible(false);
}
//更改属性值
for (Field field : fields) {
String type=field.getGenericType().toString();
String name=field.getName();
field.setAccessible(true);
if((type.equals("class java.lang.String"))&&(name.equals("name"))){
field.set(student, "李四");
}else if ((type.equals("int"))&&(name.equals("age"))) {
field.set(student, 20);
}else if((type.equals("char"))&&(name.equals("sex"))) {
field.set(student, '女');
}
field.setAccessible(false);
}
System.out.println("-------------------------------------");
System.out.println(student.toString());
}
}
通过反射机制获取某个类的所有属性,打印属性值,并思考以下问题:可以更改属性值吗?
最新推荐文章于 2022-08-16 07:15:00 发布