反射的基本API

來源:互聯網
上載者:User
反射思想由來已久,由於一直對java中反射的用法一直不太熟悉,特地找了一些資料學習了 一下,現在通過以下一些執行個體,對java中反射機制的一些用法做一些介紹:

獲得執行個體對象的一個field,method,constructor

下面是一個簡單的例子:

package reflection;

import java.lang.reflect.Field;

public class GetFieldSimple {

public int height;

private int width;

public GetFieldSimple(int height, int width) {

super();

this.height = height;

this.width = width;

}

static void printHeight(GetFieldSimple gfs){

Field heigthField;

Method method;

Constructor cons;

Integer height;

Class c =gfs.getClass(); //獲得運行時對象

//省略了try catch的代碼

heigthField=c.getField("height"); //獲得指定的欄位封裝為對象

height = heigthField.getInt(gfs); //從對象中取出欄位值

System.out.println(height);

heigthField=c.getDeclaredField("width");//width是private型

height = heigthField.getInt(gfs);

System.out.println(height);

method=c.getMethod("printMethodName1");

System.out.println("method name"+method.getName());

method=c.getDeclaredMethod("printMethodName2");//printMethodName2 //是private型

System.out.println("method name"+method.getName());

cons=c.getConstructor(new Class[] {int.class,int.class});

System.out.println("cons "+cons.getName() +" "+cons.getTypeParameters());

}

public static void main(String[] args) {

GetFieldSimple gg = new GetFieldSimple(100, 200);

printHeight(gg);

}

}

運行後會報java.lang.NoSuchFieldException: width這個錯誤,這是因為width是一個private類型。

c.getField(“***”)這個方法可以返回c所表示的類或介面的所有的公用欄位。

c.getDeclaredField("xxxx");返回已聲明的field(包括private類型)。

Method中的getMethod() 獲得public方法和getDelcaredMethod()可以獲得所有。

static欄位可以直接從類中取而不需要從對象中取等

更詳細的用法,可以去多看看API。這個只是最簡單的一個例子。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.