package com.liu.test03;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
/**
* @author : liu
* 日期:15:46:06
* 描述:IntelliJ IDEA
* 版本:1.0
*/
public class Test02 {
//这是一个main方法:是程序的入口
public static void main(String[] args) throws Exception {
//获取运行时类的字节码信息
Class cls=Student.class;
//获取属性:
//getFields获取运行时类和父类中被public修饰的属性
Field[] fields = cls.getFields();
for (Field field:fields
) {
System.out.println(field);
}
System.out.println("--------------------");
//getDeclaredFields获取运行时类中的所有属性
Field[] declaredFields = cls.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
System.out.println("---------------");
//获取指定的属性
Field name = cls.getField("name");
System.out.println(name);
Field sno = cls.getDeclaredField("sno");
System.out.println(sno);
System.out.println("------------------");
//属性的具体结构:
//获取修饰符
int modifiers = name.getModifiers();
System.out.println(modifiers);
System.out.println(Modifier.toString(modifiers));
System.out.println(Modifier.toString(name.getModifiers()));
//获取属性的类型
Class aClass = name.getType();
System.out.println(aClass.getName());
//获取属性的名字:
String name1 = name.getName();
System.out.println(name1);
System.out.println("--------------------");
//给属性赋值:(给属性设置值必须要有对象)
Field sco = cls.getField("score");
Object obj = cls.newInstance();
sco.set(obj,98);//给obj这个对象的score属性设置具体的值,这个值为98
System.out.println(obj);
}
}