Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a nested field

I'm new of reflection and I'm trying to get a nested field. Summarizing I have the following classes:

public class Agreement{

    private Long id;

    private String cdAgreement;

    private Address address;

    //Constructor getter and setter

}

public class Address{

    private Long id;

    private String description;

    //Constructor getter and setter

}

Now I want to get the description field, then i wrote this code:

Agreement agreement = new Agreement();
Class c = agreement.getClass();
Field f = c.getDeclaredField("address.descritpion");

but not works, I get the following exception:

java.lang.NoSuchFieldException: address.descritpion
at java.lang.Class.getDeclaredField(Class.java:1948)

Where am I doing wrong?

like image 419
Skizzo Avatar asked May 07 '14 09:05

Skizzo


People also ask

What is a nested field?

When a packed class contains an instance field that is a packed type, the data for that field is packed directly into the containing class. The field is known as a nested field . When reading from a nested field, a small object is created as a pointer to the data.

How do I search in nested fields?

You can search nested fields using dot notation that includes the complete path, such as obj1.name . Multi-level nesting is automatically supported, and detected, resulting in an inner nested query to automatically match the relevant nesting level, rather than root, if it exists within another nested query.

What are nested fields in elasticsearch?

The nested type is a specialised version of the object data type that allows arrays of objects to be indexed in a way that they can be queried independently of each other.

What is nested datatype?

Nested data types are structured data types for some common data patterns. Nested data types support structs, arrays, and maps. Popular query engines such as Hive, Spark, Presto, and Redshift Spectrum support nested data types. The SQL syntax those engines support can be different.


1 Answers

The current problem is that no field has the name "address.description" (it's not even a valid name for a field).

You have to get the address field first, access its class, and get the nested field from there. To do so, use getType():

Agreement agreement = new Agreement();
Class c = agreement.getClass();          // Agreement class
Field f = c.getDeclaredField("address"); // address field
Class<?> fieldClass = f.getType();       // class of address field (Address)
Field nested = fieldClass.getDeclaredField("description"); // description field

You can also chain the calls without local variables:

Field nested = c.getDeclaredField("address").getType().getDeclaredField("description");
like image 90
Joffrey Avatar answered Oct 05 '22 19:10

Joffrey