I have a class named Attributes, which has some instance variables as listed below:
public class Attributes {
protected A variable1;
protected B variable2;
protected C variables3;
/*
Getters and Setters of each method.
*/
}
I want the list of all instance variables' types present in the class.
The output: [A,B,C]
This contains all possible dataTypes present in this class.
Can someone please suggest a way?
NOTE: I've seen reflection, but I think it is useful only if we have filled the values for these variables and we want to fetch the values and names of those variables, not the types.
CodePudding user response:
You can use reflection to access the Field
and then get it's type:
See: Field.getType() && Class.getDeclaredFields()
CodePudding user response:
You can use reflection
to get the type
like that:
class Scratch {
public static class Test {
private int a;
private long b;
}
public static void main(String[] args) {
Field[] fields = Test.class.getDeclaredFields();
for (int i = 0; i < fields.length; i ) {
System.out.println("Type: " fields[i].getType());
}
}
}
Output:
Type: int
Type: long
CodePudding user response:
You simply can use the reflection method getType(). In order to get a list of all instance types it's as simple as:
Arrays.stream(Attributes.class.getDeclaredFields()).map(Field::getType).collect(Collectors.toList())
Where the getFields()
will return the array of all the fields within the class (and not its instances, you are referencing the class and not the instance of the class).
The map()
part will map the field to its class type.
And the collect(Collectors.toList())
will just get the stream result of Class<?> type to a List. If you don't want only the single class types, so no duplicates just use toSet()
instead.