Java>反射 案例:在不改变该类的任何代码的前提下,帮我们创建任意类的对象,并且执行其中任意方法

Person类

public class Person {
    
    
    public String str_name;
    public Integer str_age;
    private String ID_card_number;

    public Person() {
    
    
    }

    public Person(String str_name, Integer str_age, String ID_card_number) {
    
    
        this.str_name = str_name;
        this.str_age = str_age;
        this.ID_card_number = ID_card_number;
    }

    public String getStr_name() {
    
    
        return str_name;
    }

    public void setStr_name(String str_name) {
    
    
        this.str_name = str_name;
    }

    public Integer getStr_age() {
    
    
        return str_age;
    }

    public void setStr_age(Integer str_age) {
    
    
        this.str_age = str_age;
    }

    public String getID_card_number() {
    
    
        return ID_card_number;
    }

    public void setID_card_number(String ID_card_numver) {
    
    
        this.ID_card_number = ID_card_numver;
    }


    public void eat(int a){
    
    
        System.out.println("Cat eat fish ~~~" + a);
    }
    public void eat1(int a){
    
    
        System.out.println("My eat fish ~~~" + a);
    }
}
ClassName=com.dome.Person
MethodName=eat

pro.properties

实现代码部分

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Create_EveryObject {
    
    
    public static void main(String[] args) throws NoSuchMethodException, IOException, ClassNotFoundException, InvocationTargetException, IllegalAccessException, InstantiationException {
    
    
        // 创建类加载器
        ClassLoader classLoader = Create_EveryObject.class.getClassLoader();
        // 获取需要的静态资源
        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");

        // 创建Properties对象,加载静态资源
        Properties properties = new Properties();
        properties.load(resourceAsStream);

        // 获取类名和方法名字
        String className = properties.getProperty("ClassName");
        String methodName = properties.getProperty("MethodName");
        System.out.println(className);
        System.out.println(methodName);

        // 加载字节码文件
        Class<?> aClass = Class.forName(className);
        // 通过字节码文件,获取对象
        Object object = aClass.getDeclaredConstructor().newInstance();

        // get method object
        Method method = aClass.getMethod(methodName,int.class);
        method.invoke(object,18);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43309893/article/details/116372322