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?
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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With