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調用方法的時候附帶上參數。(這里偷工減料參數直接寫了,最好也是通過配置動態加載進來

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM