【反射】反射快速入门

创建Cat对象

package com.reflection.domain;

public class Cat {
    private String name = "小喵";

    public void hi() {
        System.out.println("hi " + name);
    }

    public void cry() {
        System.out.println(name + " cry");
    }
}

编写re.properties文件

classfullpath=com.reflection.domain.Cat
method=cry

反射应用

package com.reflection;

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

public class Main {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\re.properties"));
        String classfullpath = properties.get("classfullpath").toString();
        String methodName = properties.get("method").toString();

        System.out.println("classfullpath:" + classfullpath);
        System.out.println("methodName:" + methodName);

        Class cls = Class.forName(classfullpath);
        Object o = cls.newInstance();

        Method hiMethod = cls.getMethod(methodName);

        hiMethod.invoke(o);
    }
}
posted @ 2022-09-28 21:20  xl4ng  阅读(15)  评论(0)    收藏  举报