Java学习:反射

反射

使用反射可以直接获取class字节码文件中的类型、属性、方法。

演示代码:

新建一个名为User的类作为反射的操作对象

public class User {
    private int id;
    private String name;
    private String password;
    public User() {
    
    }
    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @return the password
     */
    public String getPassword() {
        return password;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
    }
    
    
}

演示

获取类

Object u = new User();
Class class1 = u.getClass();

获取类名

class1.getName()

获取类访问权限

int modifier = class1.getModifiers();
boolean flag = Modifier.isPublic(modifier);
System.out.println("是public?: "+flag);

属性

获取类所有属性
访问权限私有的也可以获取到

Field[] arr = class1.getDeclaredFields();
for (Field field:arr) {
    System.out.println ("类中的属性:" + field);
}

获取类所有属性的值
私有属性默认无法获取,但是可以通过不检查访问权限来直接获取。

// 获取所有属性的值
for (Field field:arr) {
    // 不检查访问权限
    field.setAccessible(true);
    // 获取u对象中field的值
    Object o = field.get(u);
    System.out.println("类中的属性值:" +o);
}

指定属性名获取属性

Field f = class1.getDeclaredField("name");
f.setAccessible(true);
f.set(u, "张三");
Object o = f.get(u);
System.out.println("name: " + o);

方法

获取所有方法(包含从父类继承的方法)

Method[] allMethods = class1.getMethods();
System.out.println("类的所有方法:");
for (Method method:allMethods) {
    System.out.println(method);
}

获取类自己的方法

Method[] onlyMethods = class1.getDeclaredMethods();
for (Method method:onlyMethods) {
    System.out.println(method);
}

调用无参带返回值方法

Method method2 = class1.getDeclaredMethod("getName");
String str = (String)(method2.invoke(u));
System.out.println ("返回值:"+ str);

调用有参无返回值方法

Method method = class1.getDeclaredMethod("setName", String.class);
method.invoke(u, "李四");

完整演示代码:

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class ReflectTest {
    public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, InvocationTargetException {
        Object u = new User();
        // 获取到User的类
        Class class1 = u.getClass();
        
        System.out.println("类名:"+class1.getName());
        
        // 获取类访问权限
        int modifier = class1.getModifiers();
        boolean flag = Modifier.isPublic(modifier);
        System.out.println("是public?: "+flag);
        
        // 获取所有属性
        Field[] arr = class1.getDeclaredFields();
        for (Field field:arr) {
            System.out.println ("类中的属性:" + field);
        }
        // 获取所有属性的值
        for (Field field:arr) {
            // 不检查访问权限
            field.setAccessible(true);
            // 获取u对象中field的值
            Object o = field.get(u);
            System.out.println("类中的属性值:" +o);
        }
        
        // 指定字段名称获取属性
        Field f = class1.getDeclaredField("name");
        f.setAccessible(true);
        f.set(u, "张三");
        Object o = f.get(u);
        System.out.println("name: " + o);
        
        // 获取所有方法 (包含继承方法)
        Method[] allMethods = class1.getMethods();
        System.out.println("类的所有方法:");
        for (Method method:allMethods) {
            System.out.println(method);
        }
        // 获取当前类的自己的方法
        Method[] onlyMethods = class1.getDeclaredMethods();
        for (Method method:onlyMethods) {
            System.out.println(method);
        }
        
        // 调用有参方法
        Method method = class1.getDeclaredMethod("setName", String.class);
        method.invoke(u, "李四");
        
        // 调用无参有返回值方法
        Method method2 = class1.getDeclaredMethod("getName");
        String str = (String)(method2.invoke(u));
        System.out.println ("返回值:"+ str);
        
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章