阅读67 返回首页    go 阿里云 go 技术社区[云栖]


Java Reflection(六):Getters and Setters

使用Java反射你可以在运行期检查一个方法的信息以及在运行期调用这个方法,使用这个功能同样可以获取指定类的getters和setters,你不能直接寻找getters和setters,你需要检查一个类所有的方法来判断哪个方法是getters和setters。

首先让我们来规定一下getters和setters的特性:

Getter

Getter方法的名字以get开头,没有方法参数,返回一个值。

Setter

Setter方法的名字以set开头,有一个方法参数。

setters方法有可能会有返回值也有可能没有,一些Setter方法返回void,一些用来设置值,有一些对象的setter方法在方法链中被调用(译者注:这类的setter方法必须要有返回值),因此你不应该妄自假设setter方法的返回值,一切应该视情况而定。

下面是一个获取getter方法和setter方法的例子:

01 </pre>
02 <pre class="codeBox">public static void printGettersSetters(Class aClass){
03   Method[] methods = aClass.getMethods();
04  
05   for(Method method : methods){
06     if(isGetter(method)) System.out.println("getter: " + method);
07     if(isSetter(method)) System.out.println("setter: " + method);
08   }
09 }
10  
11 public static boolean isGetter(Method method){
12   if(!method.getName().startsWith("get"))      return false;
13   if(method.getParameterTypes().length != 0)   return false;
14   if(void.class.equals(method.getReturnType()) return false;
15   return true;
16 }
17  
18 public static boolean isSetter(Method method){
19   if(!method.getName().startsWith("set")) return false;
20   if(method.getParameterTypes().length != 1return false;
21   return true;
22 }</pre>
23 <pre>

最后更新:2017-05-23 12:02:36

  上一篇:go  《GO并发编程实战》—— 临时对象池
  下一篇:go  并发数据结构-1.1 并发的数据结构的设计