• Java Reflection(六):Getters and Setters


    转载自并发编程网 – ifeve.com

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

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

    Getter

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

    Setter

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

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

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

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

     

    原文地址 作者: Jakob Jenkov 译者:叶文海(yewenhai@gamil.com)

  • 相关阅读:
    ZOJ
    CodeForces
    模板
    前门
    错误记录
    2021/1/10例会 academy of management journal 2014vol 57 No.2,484-514
    Day7下
    Day7上
    Day6 下(
    Day6上 括号匹配专项
  • 原文地址:https://www.cnblogs.com/rmsSpring/p/4615457.html
Copyright © 2020-2023  润新知