java動的反射呼び出し方法-の------構成ファイルのクラスのパスと方法名に基づいて方法を呼び出します。

2882 ワード

1.まず反射入門例
 //          ,        
    @Test
    public void ReflectCase() throws Exception {
        /**
         *     
         *  1.      .        
         *  2.  class     
         *  3.    
         *  4.    
         */
        Properties properties=new Properties();
        //      
        /*ClassLoader classLoader = Demo02ReflectCaseTest.class.getClassLoader();
        //            
        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");*/
        FileReader fileReader = new FileReader("src\\cn\\web\\day01\\test\\pro.properties");
        properties.load(fileReader);
        //      
        String className = properties.getProperty("className");
        //     
        String methodName = properties.getProperty("methodName");
        //        -       
        Class> aClass = Class.forName(className);
        //    
        Object o = aClass.newInstance();
        //    
        Method declaredMethod = aClass.getDeclaredMethod(methodName);
        declaredMethod.invoke(o);

    }
2.動的反射呼び出し方法1.プロファイルプロ.properties
className=cn.web.day01.reflect.Student
methodName=study
2.methodReflectUtilsツール類を定義する

/**
 *     
 */
public class methodReflectUtils {
    /**
     *                       
     * @param className
     *                    
     * @param methodName
     *                   
     * @param args
     *               
     */
    public static void methodReflect(String className, String methodName, Object[] args) {

        Class[] argsClass = new Class[args.length];

        for(int i=0; i
3.試験類の試験方法を定義する
 //          ,        
    @Test
    public void ReflectCase() throws Exception {
        Properties properties=new Properties();
        //      
        /*ClassLoader classLoader = Demo02ReflectCaseTest.class.getClassLoader();
        //            
        InputStream resourceAsStream = classLoader.getResourceAsStream("pro.properties");*/
        FileReader fileReader = new FileReader("src\\cn\\web\\day01\\test\\pro.properties");
        properties.load(fileReader);
        //      
        String className = properties.getProperty("className");
        //     
        String methodName = properties.getProperty("methodName");

        //      
        Object []args={"  ",9};
        methodReflectUtils.methodReflect(className,methodName,args);
        //      
        Object []args1={};
        methodReflectUtils.methodReflect(className,methodName,args1);

    }