Java 反射的基本應用

來源:互聯網
上載者:User

標籤:blog   row   擷取   sts   out   tty   res   read   ddr   

package com.lf.testreflection;import java.lang.reflect.Field;import java.lang.reflect.Method;import org.junit.Test;public class ClassTest{        @Test    public void testSomthing()throws Exception {        //建立運行時類的對象        Class cla = Person.class;        // 建立運行時Person的對象        Person person = (Person)cla.newInstance();        // 通過cla擷取對象的屬性        Field field = cla.getDeclaredField("name");        // 設定可以訪問的許可權        field.setAccessible(true);        // 設定相應的屬性值        field.set(person, "kity");        //擷取相應的屬性(public可以使用下面方法擷取)        field = cla.getField("address");        field.set(person, "NewYo");        field = cla.getDeclaredField("age");        field.setAccessible(true);        field.set(person, 18);                System.out.println(person);        // 擷取無參方法        Method method = cla.getMethod("learn");        method.invoke(person);        // 擷取有參方法        Method method2 =cla.getMethod("readSomething",String.class);        method2.invoke(person, "ainsy");        // 擷取多參方法        Method method3 =cla.getMethod("readSomething",int.class,String.class);        method3.invoke(person, 20,"ainsy");        // 擷取所有的屬性        Field[] fields = cla.getDeclaredFields();        for (Field field2 : fields) {            // 每個屬性的修飾符            System.out.print(field2.getModifiers()+"  ");            // 每個屬性名稱            System.out.print(field2.getName()+"  ");            // 擷取屬性的類型            Class type = field2.getType();            System.out.println(type);        }                    // 調用運行時本身的.class屬性        Class cla2 = Person.class;        //列印類路徑        System.out.println(cla2.getName());                // 通過運行時類的對象擷取        Person p = new Person();        Class cla3 = p.getClass();        System.out.println(cla3.getName());    }}

 

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.