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方法的例子:

//java学习交流:737251827  进入可领取学习资源及对十年开发经验大佬提问,免费解答!
</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>

《Java Reflection(一):Java反射指南》Java Reflection(六):Getters and Settershttps://shimo.im/docs/hHvvCkq3VqdtHG8d  

《    Java Reflection(二):Classes   》Java Reflection(六):Getters and Settershttps://shimo.im/docs/pg6JgCjyhRDDGvWJ/ 

《       Java Reflection(三):构造器     》Java Reflection(六):Getters and Settershttps://shimo.im/docs/6YY38vCVTtXkgKC8/ 

《        Java Reflection(四):变量       》Java Reflection(六):Getters and Settershttps://shimo.im/docs/dWRhHPgKwrjDdx3P/ 

《        Java Reflection(五):方法       》 Java Reflection(六):Getters and Settershttps://shimo.im/docs/ThKHpxvJGkqGCDkr/ 

上一篇:Java的反射机制-动态调用对象的方法


下一篇:laravel源码解析之请求处理流程