Java Reflection(六):Getters and Setters

原文地址 作者: Jakob Jenkov 譯者:葉文海([email protected]
使用Java反射你可以在運行期檢查一個方法的信息以及在運行期調用這個方法,使用這個功能同樣可以獲取指定類的getters和setters,你不能直接尋找getters和setters,你需要檢查一個類所有的方法來判斷哪個方法是getters和setters。

首先讓我們來規定一下getters和setters的特性:

1. Getter

Getter方法的名字以get開頭,沒有方法參數,返回一個值。

2. Setter

Setter方法的名字以set開頭,有一個方法參數。

setters方法有可能會有返回值也有可能沒有,一些Setter方法返回void,一些用來設置值,有一些對象的setter方法在方法鏈中被調用(譯者注:這類的setter方法必須要有返回值),因此你不應該妄自假設setter方法的返回值,一切應該視情況而定。

下面是一個獲取getter方法和setter方法的例子:

</pre>

<pre class="codeBox">public static void printGettersSetters(Class aClass){

  Method[] methods = aClass.getMethods();


  for(Method method : methods){

 if(isGetter(method)) System.out.println("getter: " + method);

  if(isSetter(method)) System.out.println("setter: " + method);

  }

}



public static boolean isGetter(Method method){

  if(!method.getName().startsWith("get"))      return false;

  if(method.getParameterTypes().length != 0)   return false;

  if(void.class.equals(method.getReturnType()) return false;

  return true;

}



public static boolean isSetter(Method method){

  if(!method.getName().startsWith("set")) return false;

  if(method.getParameterTypes().length != 1) return false;

  return true;

}</pre>

<pre>

原創文章,轉載請註明: 轉載自併發編程網 – ifeve.com

本文鏈接地址: Java Reflection(六):Getters and Setters

發佈了46 篇原創文章 · 獲贊 6 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章