第六課 JAVA反射擷取對象屬性和方法(通過設定檔)

來源:互聯網
上載者:User

標籤:get   類對象   test   raw   指定   tco   txt   style   執行個體化   

Service1.java

package reflection; public class Service1 {     public void doService1(){        System.out.println("業務方法1");    }}

Service2.java

package reflection; public class Service2 {     public void doService2(){        System.out.println("業務方法1");    }}

spring.txt(D:\spring)

class=reflection.Service1method=doService1

Test.java

package reflection; import java.io.File;import java.io.FileInputStream;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.util.Properties; public class Test {     @SuppressWarnings({ "rawtypes", "unchecked" })    public static void main(String[] args) throws Exception {         //從spring.txt中擷取類名稱和方法名稱        File springConfigFile = new File("d:\\spring.txt");        Properties springConfig= new Properties();        springConfig.load(new FileInputStream(springConfigFile));        String className = (String) springConfig.get("class");        String methodName = (String) springConfig.get("method");                 //根據類名稱建立類對象        Class clazz = Class.forName(className);        //根據方面名稱,擷取方法        Method m = clazz.getMethod(methodName);        //擷取構造器        Constructor c = clazz.getConstructor();        //根據構造器,執行個體化出對象        Object service = c.newInstance();        //調用對象的指定方法        m.invoke(service);             }}

 

第六課 JAVA反射擷取對象屬性和方法(通過設定檔)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.