Domanda

Ho un metodo che ottiene un POJO come parametro. Ora voglio ottenere a livello di codice tutti gli attributi del POJO (perché il mio codice potrebbe non sapere quali sono tutti gli attributi in esso in fase di esecuzione) e ho bisogno di ottenere anche i valori per gli attributi. Infine formerò una rappresentazione in formato stringa del POJO.

Potrei usare ToStringBuilder , ma voglio costruire la mia stringa di output in un determinato formato specifico per il mio requisito.

È possibile farlo in Beanutils!? Se sì, qualche puntatore al nome del metodo? Se no, dovrei scrivere il mio codice di riflessione?

È stato utile?

Soluzione

Hai provato ReflectionToStringBuilder ? Sembra che dovrebbe fare quello che descrivi.

Altri suggerimenti

So che questa è una domanda vecchia di un anno, ma penso che possa essere utile per gli altri.

Ho trovato una soluzione parziale usando questo LOC

Field [] attributes =  MyBeanClass.class.getDeclaredFields();

Ecco un esempio funzionante:

import java.lang.reflect.Field;

import org.apache.commons.beanutils.PropertyUtils;

public class ObjectWithSomeProperties {

    private String firstProperty;

    private String secondProperty;


    public String getFirstProperty() {
        return firstProperty;
    }

    public void setFirstProperty(String firstProperty) {
        this.firstProperty = firstProperty;
    }

    public String getSecondProperty() {
        return secondProperty;
    }

    public void setSecondProperty(String secondProperty) {
        this.secondProperty = secondProperty;
    }

    public static void main(String[] args) {

        ObjectWithSomeProperties object = new ObjectWithSomeProperties();

        // Load all fields in the class (private included)
        Field [] attributes =  object.getClass().getDeclaredFields();

        for (Field field : attributes) {
            // Dynamically read Attribute Name
            System.out.println("ATTRIBUTE NAME: " + field.getName());

            try {
                // Dynamically set Attribute Value
                PropertyUtils.setSimpleProperty(object, field.getName(), "A VALUE");
                System.out.println("ATTRIBUTE VALUE: " + PropertyUtils.getSimpleProperty(object, field.getName()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

ottieni tutte le proprietà / variabili (solo il nome) usando reflection. Ora usa metodo getProperty per ottenere il valore di quella variabile

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top