Main.Java : Main Class which creating the object of Test which of generic type Test.Java: Its Generic class which is creating object of Wrapper class of generic type Wrapper.java: Its a Generic Class of Type We are passing String,Long as type for creating Test.java object . And passing long as a type for creating the object of Wrapper class. Main.Java:
public class MainClass {
Test<String,Long> test;
MainClass()
{
test = new Test<String,Long>(){};
}
public static void main(String[] arr)
{
MainClass m = new MainClass();
}
}
Test.Java
public class Test<T,U>
{
Wrapper<U> mywrapper;
Test()
{
Type type = this.getClass().getGenericSuperclass();
System.out.println("TYPE: " + type.toString());
Type type1 = ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
System.out.println("TYPE1: " + type1.getClass().getName());
Type[] types = ((ParameterizedType)type).getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
System.out.println("TYPES[" + i + "]: " + types[i].toString());
}
mywrapper = new Wrapper<U>(){};
}
}
Wrapper.Java
public class Wrapper<U> {
Wrapper()
{
Type type = this.getClass().getGenericSuperclass();
System.out.println("TYPE: " + type.toString());
Type type1 = ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
System.out.println("TYPE1: " + type1.getClass().getName());
Type[] types = ((ParameterizedType)type).getActualTypeArguments();
for (int i = 0; i < types.length; i++) {
System.out.println("TYPES[" + i + "]: " + types[i].toString());
}
}
}
And after executing the program we are getting output as
TYPE: Test
TYPE1: java.lang.Class
TYPES[0]: class java.lang.String
TYPES[1]: class java.lang.Long
TYPE: Wrapper
*TYPE1: sun.reflect.generics.reflectiveObjects.TypeVariableImpl
TYPES[0]: U*
So from the output you can see for the Wrapper class we are getting Type as U instead of Long as you can see in Test.Java.