SoFunction
Updated on 2025-03-08

Use reflection to obtain the properties and values ​​of JPA Entity

Reflection method to obtain JPA Entity attributes and values

When recording logs or debugging, you often need to output the database query or write values, or when interacting with the interface, you may need to convert the entity into a JSON string and pass it out.

In JPA it is passed in Entity example. But if you use ()

In the method, the output result is the form of entity@ memory address, and it is impossible to know the specific internal properties and values ​​of Entity.

The following describes a method of obtaining Entity's fields and values ​​using reflection:

Reflection tool class

Take converting an entity to a JSON string as an example:

public class ReflectEntity{
    public static String toStr(Object o){
        try{
            StringBuilder sb = new StringBuilder();
            ("{");
            Class cls = ();
            Field[] fields = ();
            for(Field f : fields){
                (true);
                ("\"").append(()).append("\":\"").append((o)).append("\",");
            }
            return ("%s}",(0,()-1));
        } catch(Exception e){
            return null;
        }
    }
}

Rewrite the toString method

Suppose there is a JPA Entity:

@Entity
public class E{
    private String colA;
    private String colB;
    //getter, setter    // Just use the reflection method here    @Override
    public String toString(){
        return (this);
    }
}

After the above modification, the record or the transmission of Entity or List<Entity> can be successfully converted into a JSON string.

Get Entity's data through reflection

Application scenario: Sometimes SQL is difficult to splice (for example: not sure which field to obtain data), at this time we can use Java reflection to obtain data

Entity Class

@Entity
@Table(name = EntitlementDbConstants.CUSTOMER_MASTER_DATA_VIEW)
public abstract class CustomerMasterDataView
{
    private static final long serialVersionUID = 1963275800615627823L; 
    @ExtendField
    @Column(name = CommonHanaDbExtendsColumnConstants.S_EX_1)
    private String sEX1;
 
    @ExtendField
    @Column(name = CommonHanaDbExtendsColumnConstants.S_EX_2)
    private String sEX2;
 
    //Omit the get, set method}

2. Get Entity data through java reflection

private List&lt;Map&lt;String, Object&gt;&gt; getExtensionAttributeValue(List&lt;CustomerMasterDataView&gt; customerMasterDataViews, String field, String type)
    {
        List&lt;Object&gt; noRepeakValue = new ArrayList&lt;&gt;();
        List&lt;Map&lt;String, Object&gt;&gt; valueList =new ArrayList&lt;&gt;();
        Map&lt;String, Object&gt; map = null;
        Object obj = null;
        String methodName = "get" + ((field, new String[]     //Get data through get method        { "_" }, new String[]
        { "" }));
        for(CustomerMasterDataView customerMasterDataView:customerMasterDataViews)
        {
            try
            {
                Method method = ().getMethod(methodName);
                obj = (customerMasterDataView);// obj is when we get the value of a certain field            }
            catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
            {
                if (())
                    ("Could not reflect the method {}", methodName, e);
            }
            map = formatAttributeValue(obj, type, noRepeakValue);    // Format data, custom method            if(null != map)
            {
                (map);
            }
        }
        return valueList;
    }

The above is personal experience. I hope you can give you a reference and I hope you can support me more.