java反射小实例

利用反射实现

对配置文件的更改达到更改方法的目的

文件夹目录

首先Student类中有个sleep方法

 pro.properties定义了参数

最后是RelectTestMain。

package com.reflex.test;

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

import javax.annotation.Resource;
import javax.annotation.Resources;

import com.reflex.bean.Person;
import com.reflex.bean.Student;

public class RelectTestMain {
    public static void  main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
        /*1、加载配置文件
         * 用类名.class.getResourceAsStream("/xx")或者
         *   类名.class.getClassLoader().getResourceAsStream("xx");
         *         区别在于前者是需要反斜杠,后者不需要
         * */
        Properties properties = new Properties();
        properties.load(RelectTestMain.class.getResourceAsStream("/pro.properties"));
        //2、获取配置文件中定义的数据
        String className = properties.getProperty("className");
        String methodName = properties.getProperty("methodName");
        //3、加载该类进内存
        Class cls = Class.forName(className);
        //4、创建类对象
        Object obj = cls.newInstance();
        //5、获取对象方法
        Method method = cls.getMethod(methodName);
        //6、执行方法
        method.invoke(obj);
    }
}
View Code

如果需要传入参数,则在获取对象的时候使用getDeclaredMethod方法,附上参数类的class,最后再在invork调用方法的时候附带上参数。(这里偷工减料参数直接写了,最好也是通过配置动态加载进来

原文地址:https://www.cnblogs.com/Esquecer/p/11126720.html