Suppose to have a type Pair<K,V>
declared in your package. Given an object instance of:
Pair<Integer, Integer> obj = new Pair<>(1,23);
I want to retrieve the type arguments Integer
and Integer
to which K
and V
are respectively associated. By the way, it seems to be that using Java standard reflection I cannot access to the actual class with the instances within Java.
TypeVariable<? extends Class<?>>[] parameters = obj.getClass().getTypeParameters();
I did not manage to extract such desired information using such parameters. I start to wonder, maybe the type information is kept only at compile time, while at run time the actual type parameter information is removed.
If you just have an instance, as you exemplified: Pair<Integer, Integer> pair = new Pair<>(1,23)
, there's no way to get the static generic types as that information is lost in runtime.
If, on the other hand, Pair<Integer, String>
was the type of a field, method return type, the type of a method parameter, or if the generic type arguments came from the superclass, it would be possible to extract the static generic types.
Check my answer here for examples on extracting generic types in these cases.
Short of that, you can only check the dynamic types of the values in runtime, as explained by Yahya.
Please consider this answer:
public static String[] getArgumentType(Object obj){
String[] type = new String[2];
type[0]=((Pair<?, ?>) obj).getKey().getClass().getName().replace("java.lang.", "");
type[1]=((Pair<?, ?>) obj).getValue().getClass().getName().replace("java.lang.", "");
return type;
}
public static void main(String[] args) {
Pair<String,Integer> obj = new Pair<String,Integer>("", 2);
String[] type = getArgumentType(obj);
System.out.println(type[0] + ", " + type[1]);
Pair<Integer,Integer> obj1 = new Pair<Integer,Integer>(1, 2);
type = getArgumentType(obj1);
System.out.println(type[0] + ", " + type[1]);
Pair<Double,Float> obj2 = new Pair<Double,Float>(1.1, 2.2f);
type = getArgumentType(obj2);
System.out.println(type[0] + ", " + type[1]);
Pair<Person,Object> obj3 = new Pair<Person,Object>(new Person(), new Object());
type = getArgumentType(obj3);
System.out.println(type[0] + ", " + type[1]);
}
The Output:
String, Integer
Integer, Integer
Double, Float
Person, Object