Java Reflection(六):Getters and Setters

195 篇文章 2 订阅
108 篇文章 0 订阅

使用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反射指南》icon-default.png?t=LA92https://shimo.im/docs/hHvvCkq3VqdtHG8d  

《    Java Reflection(二):Classes   》icon-default.png?t=LA92https://shimo.im/docs/pg6JgCjyhRDDGvWJ/ 

《       Java Reflection(三):构造器     》icon-default.png?t=LA92https://shimo.im/docs/6YY38vCVTtXkgKC8/ 

《        Java Reflection(四):变量       》icon-default.png?t=LA92https://shimo.im/docs/dWRhHPgKwrjDdx3P/ 

《        Java Reflection(五):方法       》 icon-default.png?t=LA92https://shimo.im/docs/ThKHpxvJGkqGCDkr/ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值