初识反射 Java
Java学习笔记 初识反射
- 反射可以让程序更具有动态性
反射Api的简单使用
首先创建一个User类和一个TestClass类用来演示反射的动态加载,本篇笔记以代码为主
User
package com.bean;
public class User {
private int id;
private String userName;
private int age;
public User() {
}
public User(int id, String userName, int age) {
this.id = id;
this.userName = userName;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", age=" + age +
'}';
}
}
TestClass
import com.bean.User;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
public class TestClass {
public static void main(String[] args) {
String path ="com.bean.User";
try {
Class clazz = Class.forName(path);
//反射API获得所有的属性
Field[] fileds = clazz.getDeclaredFields();
System.out.println(Arrays.toString(fileds));
//反射API获得所有的构造器,但构造器必须为公用的才能获取
Constructor[] constructors = clazz.getConstructors();
//向控制打印获得的构造器
System.out.println(Arrays.toString(constructors));
//反射API获得所有声明的构造器getDeclaredConstructors不局限于共有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
//向控制打印获得的构造器
System.out.println(Arrays.toString(declaredConstructors));
//反射API获取无参构造器
Constructor declaredConstructor = clazz.getDeclaredConstructor();
//向控制打印获得的构造器
System.out.println(declaredConstructor);
//反射API获取有参构造器并实例化一个对象user打印在控制台上
Constructor declaredConstructor1 = clazz.getDeclaredConstructor(int.class, String.class, int.class);
User user= (User)declaredConstructor1.newInstance(1,"二狗",20);
System.out.println(user);
//反射API实例化一个user1对象
User user1 =(User) clazz.newInstance();
//反射API获得所有的方法
Method[] mthtods = clazz.getDeclaredMethods();
//打印所有的方法
System.out.println(Arrays.toString(mthtods));
//反射API为方法传输参数
Method method = clazz.getDeclaredMethod("setUserName", String.class);
method.invoke(user1,"张三");
System.out.println(user1.getUserName());
User user2=(User)clazz.newInstance();//实例化一个对象user2
Field field = clazz.getDeclaredField("userName");//用反射API获得属性
field.setAccessible(true);//告诉编译器不用进行安全检查
field.set(user2,"李四");//给属性设置
System.out.println(field.get(user2));//打印与下面的打印语句作用一样
System.out.println(user2.getUserName());
} catch (Exception e) {
e.printStackTrace();
}
}
}