2010-04-14 25 views
99

Necesito obtener el valor de un campo con una anotación específica, por lo que con la reflexión puedo obtener este objeto de campo. El problema es que este campo siempre será privado, aunque sé de antemano que siempre tendrá un método getter. Sé que puedo usar setAccesible (true) y obtener su valor (cuando no hay ningún PermissionManager), aunque prefiero invocar su método getter.La mejor forma de invocar getter por reflexión

Sé que podría buscar el método buscando "get + fieldName" (aunque sé, por ejemplo, que los campos booleanos a veces se denominan "is + fieldName").

Me pregunto si hay una mejor manera de invocar este getter (muchos frameworks usan getters/setters para acceder a los atributos, tal vez lo hagan de otra manera).

Gracias

Respuesta

195

creo que esto se debe apuntar hacia la dirección correcta:

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)); 
} 

Tenga en cuenta que usted podría crear BeanInfo o PropertyDescriptor casos a sí mismo, es decir, sin utilizar Introspector. Sin embargo, Introspector hace un poco de almacenamiento en caché internamente, que normalmente es una buena cosa (tm). Si usted es feliz sin una memoria caché, puede incluso ir a

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

Sin embargo, hay una gran cantidad de librerías que ampliar y simplificar la API java.beans. Commons BeanUtils es un ejemplo bien conocido. Allí, simplemente lo haría:

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

BeanUtils viene con otras cosas prácticas. es decir, conversión de valor sobre la marcha (objeto a cadena, cadena a objeto) para simplificar las propiedades de configuración de la entrada del usuario.

+2

+1 simplemente correcto ... totalmente correcto;) – BalusC

+0

¡Muchas gracias! Esto me ahorró manipulaciones de cadenas, etc. – guerda

+1

Buena llamada en BeanUtils de Apache. Facilita la obtención/configuración de propiedades y maneja la conversión de tipos. –

4

La convención de nomenclatura es parte de la especificación bien establecida JavaBeans y se apoya en los clases del paquete java.beans.

15

Puede utilizar Reflections marco para este

import static org.reflections.ReflectionUtils.*; 
Set<Method> getters = ReflectionUtils.getAllMethods(someClass, 
     withModifier(Modifier.PUBLIC), withPrefix("get"), withAnnotation(annotation)); 
3

Puede invocar reflexiones y también, el orden de la secuencia establecida para captador de valores por medio de anotaciones

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(); 
} 

}

Salida cuando ordenados

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