基本介绍
package top.ltyzqhh.Class;
import top.ltyzqhh.Car;
import java.lang.reflect.Field;
public class Class01 {
public static void main(String[] args) throws Exception{
String classAllPath="top.ltyzqhh.Car";
//获取到Car类对应的Class对象,还没有实例化
Class cls = Class.forName(classAllPath);
//得到包名
System.out.println(cls.getPackage().getName());//包名
//得到全类名
System.out.println(cls.getName());
//通过cls创建对象实例
//Car o = (Car) cls.newInstance();jdk9淘汰了
Car o = (Car)cls.getDeclaredConstructor().newInstance();
System.out.println(o);//o.toString()
//通过反射获取属性(公有)
Field brand = cls.getField("brand");
System.out.println(brand.get(o));
//通过反射给属性赋值
brand.set(o,"奔驰");
System.out.println(brand.get(o));
//遍历得到所有字段属性
Field[] fields = cls.getFields();
for (Field f:fields) {
System.out.println(f.getName());
}
}
}