2010-03-17 14 views
25

Estoy usando la versión Java de Google App Engine.¿Cómo puedo iterar sobre los miembros de la clase?

Me gustaría crear una función que pueda recibir como parámetros muchos tipos de objetos. Me gustaría imprimir las variables miembro del objeto. Cada objeto (s) puede ser diferente y la función debe funcionar para todos los objetos. ¿Tengo que usar la reflexión? Si es así, ¿qué tipo de código debo escribir?

public class dataOrganization { 
    private String name; 
    private String contact; 
    private PostalAddress address; 

    public dataOrganization(){} 
} 

public int getObject(Object obj){ 
    // This function prints out the name of every 
    // member of the object, the type and the value 
    // In this example, it would print out "name - String - null", 
    // "contact - String - null" and "address - PostalAddress - null" 
} 

¿Cómo escribiría la función getObject?

Respuesta

69

Sí, necesitas reflexión. Sería algo parecido a esto:

public int getObject(Object obj) { 
    for (Field field : obj.getClass().getDeclaredFields()) { 
     //field.setAccessible(true); // if you want to modify private fields 
     System.out.println(field.getName() 
       + " - " + field.getType() 
       + " - " + field.get(obj)); 
    } 
} 

Véase el reflection tutorial por más.

Cuestiones relacionadas