Java 中的反射机制

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

class Fruit {
    static {
        System.out.println("Class Fruit been init");
    }

    private String name;
    private int weight;
    public int public_field;

    public Fruit() {
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public int getWeight() {
        return weight;
    }

    public String getClassName() {
        return this.getClass().getName();
    }
}

class Apple extends Fruit {
    public Apple() {
        super();
    }
}

public class test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

        // 通过对象获得
        Apple apple = new Apple();
        Class<?> classGetByObj = apple.getClass();
        System.out.println(classGetByObj.getName());
        System.out.println(classGetByObj.hashCode());

        // 通过 <Classname>.class 获得
        Class<?> classGetByClassName = Apple.class;
        System.out.println(classGetByClassName.getName());
        System.out.println(classGetByClassName.hashCode());

        // 通过 forname 获得
        Class<?> classGetByForname = Class.forName("Apple");
        System.out.println(classGetByForname.getName());
        System.out.println(classGetByForname.hashCode());

        Field[] fields;


        // getFields: 能获取父类的字段,但是得是 public
        System.out.println("Fruit getFields:");
        fields = Class.forName("Fruit").getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }

        // 获取父类 declared 字段
        System.out.println("Fruit getDeclaredFields:");
        fields = Class.forName("Fruit").getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }

        System.out.println("Apple getFields:");
        fields = Class.forName("Apple").getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }

        // declared,也就是真的写到 .java 文件里的字段
        System.out.println("Apple getDeclaredFields:");
        fields = classGetByForname.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }


        Class classApple = Class.forName("Apple");
        Method appleSetName = classApple.getMethod("setName", String.class);
        
        appleSetName.invoke(apple, "apple");
        System.out.println(apple.getName());

    }
}

posted @ 2022-03-03 23:27  dutrmp19  阅读(29)  评论(0)    收藏  举报