使用反射(reflection)的簡單例子

來源:互聯網
上載者:User

運用反射訪問類的私人方法是一件比較有趣的事情,這個對於類的測試也很有實用價值。

例如下面的ClassA是要訪問的類 :

package reflecttest;

public class ClassA {
 private String id;
 public ClassA(String id){
  this.id = id;
 }
 public String getId() {
  return id;
 }
 private void setId(String id) {
  this.id = id;
 }
  
}

下面為實現訪問的簡單例子:

package reflecttest;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectSample {

 public static void main(String[] args) {
  try {
   //要被載入的類名,可以通過設定檔指定
   String className = "reflecttest.ClassA";
   
   //根據類名載入類
   Class c = Class.forName(className);

   //設定構造器參數
   Class[] paramTypes = new Class[1];
   paramTypes[0] = String.class;
   
   //產生構造器
   Constructor cs = c.getConstructor(paramTypes);
   
   //設定構造器參數值
   Object[] paramValue = new Object[1];
   paramValue[0] = "testID";
   
   //構造類執行個體
   Object obj = cs.newInstance(paramValue);
   
   //調用類中的方法: getId()
   String methodNameA = "getId";
   Method mA = c.getMethod(methodNameA, null);
   System.out.println(mA.invoke(obj, null));
   
   //調用類中的方法: setId()
   String methodNameB = "setId";
   Method mB = c.getMethod(methodNameB, new Class[]{String.class});   
   mB.invoke(obj, new Object[]{"newId"});
   
   //查看修改後的結果
   System.out.println(mA.invoke(obj, null));
   
   
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }

}

聯繫我們

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