Iam currently trying to create a distinct List<Class> classList
which contains all Classes of an object for example
DemoObject.java
public class DemoObject {
private Integer id;
private String name;
private BigDecimal price;
private Boolean isActive;
private List<NestedDemoObject> nested;
}
NestedDemoObject.java
public class NestedDemoObject {
private Integer id;
private String nameNest;
private Boolean isActive;
}
What i want to create is a method public List<Class> getDistinctClasses(Class cl);
which you give as input for example DemoObject.class
and returns a list with
[DemoObject.class, Integer.class, String.class, BigDecimal.class, Boolean.class, List.class, NestedDemoObject.class]
Another example for NestedDemoObject.class
would be
[NestedDemoObject.class, Integer.class, String.class, Boolean.class]
I tried to use the .getDeclaredClasses()
from Class
without any luck.
There is any way to get all nested classes from an object with Reflection API?
Any help or direction appreciated.
The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.
If you have a JavaSW object, you can obtain it's class object by calling getClass() on the object. To determine a String representation of the name of the class, you can call getName() on the class.
If you can list all of the possible instances of the class at compile time, use an enum . Show activity on this post. Show activity on this post. Use an array or a list.
The solution provided by Mark is partially correct. You're on the right way trying to retrieve the classes from declared fields. However getType()
method does not reveal the generic types.
In order to access the generic types you should use Field.getGenericType()
instead. It returns the classes as Type
objects. The Field
objects DO KNOW their own types (they are not erased as one may believe mistakenly).
This is a java 1.8+ example printing the types with generics:
Arrays.stream(DemoObject.class.getDeclaredFields())
.map(Field::getGenericType)
.map(Type::getTypeName)
.distinct()
.forEach(System.out::println);
It will print the following result:
java.lang.Integer
java.lang.String
java.math.BigDecimal
java.lang.Boolean
java.util.List<com.eto.sandbox.NestedDemoObject>
If you want to play with generic types or parse them for any reason then you could use this example:
Arrays.stream(DemoObject.class.getDeclaredFields())
.map(Field::getGenericType)
.distinct()
.forEach(type -> {
if (type instanceof Class) {
// This is a simple class
} else if (type instanceof ParameterizedType) {
// This is a generic type. You can parse its parameters recursively.
}
});
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