1.什么是反射?
就是正在运行,动态获取这个类的所有信息、
2.反射机制的作用
1.反编译: .class->.java
2.通过反射机制访问java对象的属性,方法,构造器方法等。
运用
package com.jlong.classfrorm;
import com.jlong.entity.User;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ClassFrorm {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class<?> forName = Class.forName("com.jlong.entity.User");
/* Object o = aClass.newInstance();
User user = (User) o;
System.out.println(user.toString());*/
//有参构造器初始化变量
/* Constructor<?> constructor = aClass.getConstructor(String.class);
Object jlong = constructor.newInstance("jlong");
User user = (User) jlong;
String name = user.getUserName();
System.out.println(name);*/
// 使用反射实例化对象 无参数构造函数
Object newInstance = forName.newInstance();
// 获取当前类的 userId字段
Field declaredField = forName.getDeclaredField("userName");
// 允许操作私有成员
declaredField.setAccessible(true);
// 设置值
declaredField.set(newInstance, "123");
User user = (User) newInstance;
System.out.println(user.getUserName());
}
}
package com.jlong.entity;
public class User {
private String userName;
private String userId;
public User(){
}
public User(String userName){
this.userName=userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}