通过反射调用Getter的最佳方法

154
我需要获取具有特定注释的字段的值,因此使用反射可以获取该字段对象。问题是,该字段始终为private,但我预先知道它始终具有getter方法。我知道可以使用setAccessible(true)并获取其值(当没有PermissionManager时),但我更喜欢调用其getter方法。
我知道可以通过查找“get + fieldName”来查找该方法(尽管我知道例如boolean字段有时被命名为“is + fieldName”)。
我想知道是否有更好的方法来调用此getter(许多框架使用getter / setter访问属性,因此可能会以另一种方式进行)。
谢谢
4个回答

277

我认为这应该可以指引您朝着正确的方向:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

请注意,您可以自己创建BeanInfo或PropertyDescriptor实例,而不必使用Introspector。但是,Introspector在内部执行一些缓存操作,通常这是个好事情(商标)。如果您不需要缓存,甚至可以选择

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

然而,有很多库可以扩展和简化java.beans API。Commons BeanUtils就是一个众所周知的例子。在那里,你只需要这样做:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils提供了其他方便的功能,例如即时值转换(对象到字符串,字符串到对象),以简化从用户输入设置属性的过程。


非常感谢!这让我免去了字符串操作等等的麻烦! - guerda
2
使用Apache的BeanUtils是个不错的选择。它可以更轻松地获取/设置属性,并处理类型转换。 - Peter Tseng
有没有一种方法可以按照Java文件中字段列出的顺序调用方法? - LifeAndHope
喜欢它!太棒了。 - smilyface
2
PropertyDescriptor的问题在于它要求该属性具有getter和setter,但有时您可能不想拥有其中一些。 - Lucke
显示剩余2条评论

22
您可以使用Reflections框架来实现这一点。
import static org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation));

请注意,Reflections仍然与Java 9 不兼容。此处提供更好的行为链接,包括[ClassIndex](编译时)和[ClassGraph](运行时)。 - Vadzim
这个解决方案也没有像被接受的答案中的bean Introspector一样考虑is* getters。 - Vadzim

5

4
您可以通过注解调用反射,并设置getter值的顺序。
public class Student {

    private String grade;

    private String name;

    private String id;

    private String gender;

    private Method[] methods;

    @Retention(RetentionPolicy.RUNTIME)
    public @interface Order {
        int value();
    }

    /**
     * Sort methods as per Order Annotations
     * 
     * @return
     */
    private void sortMethods() {

        methods = Student.class.getMethods();

        Arrays.sort(methods, new Comparator<Method>() {
            public int compare(Method o1, Method o2) {
                Order or1 = o1.getAnnotation(Order.class);
                Order or2 = o2.getAnnotation(Order.class);
                if (or1 != null && or2 != null) {
                    return or1.value() - or2.value();
                }
                else if (or1 != null && or2 == null) {
                    return -1;
                }
                else if (or1 == null && or2 != null) {
                    return 1;
                }
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    /**
     * Read Elements
     * 
     * @return
     */
    public void readElements() {
        int pos = 0;
        /**
         * Sort Methods
         */
        if (methods == null) {
            sortMethods();
        }
        for (Method method : methods) {
            String name = method.getName();
            if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
                pos++;
                String value = "";
                try {
                    value = (String) method.invoke(this);
                }
                catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();
                }
                System.out.println(name + " Pos: " + pos + " Value: " + value);
            }
        }
    }

    // /////////////////////// Getter and Setter Methods

    /**
     * @param grade
     * @param name
     * @param id
     * @param gender
     */
    public Student(String grade, String name, String id, String gender) {
        super();
        this.grade = grade;
        this.name = name;
        this.id = id;
        this.gender = gender;
    }

    /**
     * @return the grade
     */
    @Order(value = 4)
    public String getGrade() {
        return grade;
    }

    /**
     * @param grade the grade to set
     */
    public void setGrade(String grade) {
        this.grade = grade;
    }

    /**
     * @return the name
     */
    @Order(value = 2)
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the id
     */
    @Order(value = 1)
    public String getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     * @return the gender
     */
    @Order(value = 3)
    public String getGender() {
        return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
        this.gender = gender;
    }

    /**
     * Main
     * 
     * @param args
     * @throws IOException
     * @throws SQLException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        Student student = new Student("A", "Anand", "001", "Male");
        student.readElements();
    }
  }

排序后的输出

getId Pos: 1 Value: 001
getName Pos: 2 Value: Anand
getGender Pos: 3 Value: Male
getGrade Pos: 4 Value: A

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接