反射:将类的组成部分封装为对象
好处:解耦
获取Class对象的方式:
源代码阶段:Class.forname("全类名")
类加载阶段:通过 类名.class,多用于参数的传递
运行时阶段:getClass()方法,定义在Object,多用于对象获取字节码
package reflect.po; public class Person { private String name; private Integer age; public Person() { } public Person(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
public static void main(String[] args) throws Exception { Class clazz1 = Class.forName("reflect.po.Person"); System.out.println(clazz1);//class reflect.po.Person Person person = new Person(); person.setName("test"); Field name = clazz1.getDeclaredField("name"); name.setAccessible(true);//暴力反射,不加会IllegalAccessException System.out.println("-----"+name.get(person));//test Class<Person> clazz2 = Person.class; System.out.println(clazz2);//class reflect.po.Person Person p = clazz2.getConstructor().newInstance();//等同于clazz2.newInstance(); //Person p1 = clazz2.newInstance(); Person person1 = new Person(); Class clazz3 = person1.getClass(); System.out.println(clazz3);//class reflect.po.Person }