反射作用:运行时构造类的对象、访问类的属性、调用对象的方法。

public class User {
private String name;
private String sex;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User() {
System.out.println("this is a test...");
}
}
public class ReflectTest001 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
/**
* 1.使用反射机制创建对象
* 2.forName必须传入class类的完整路径
*/
Class<?> forName = Class.forName("Reflect.User");

// 3.newInstance使用无参构造函数创建对象
Object newInstance = forName.newInstance();
User user = (User)newInstance;
System.out.println("user:" + user);
user.setName("Jack");
System.out.println(user.getName());
}
}
/**
* 运行结果:
* this is a test... // 首先运行无参构造器
* user: Reflect.User@7852e922 // User反射地址
* Jack
*/