Main.Java:创建泛型类型 Test 对象的主类 Test.Java:它的 Generic 类,用于创建泛型类型的 Wrapper 类的对象 Wrapper.java:它是一个通用类型类 我们传递 String,Long 作为创建 Test.java 对象的类型。并传递 long 作为创建 Wrapper 类对象的类型。 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();
}
}
测试.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());
}
}
}
执行程序后,我们得到的输出为
类型:测试
TYPE1:java.lang.Class
类型[0]:类 java.lang.String
类型[1]:类 java.lang.Long
类型:包装
*TYPE1:sun.reflect.generics.ReflectiveObjects.TypeVariableImpl
类型[0]:U*
因此,从输出中您可以看到,对于 Wrapper 类,我们得到的 Type 为 U,而不是您在 Test.Java 中看到的 Long。
最佳答案
希望下面的节目能够解答您的疑惑。
public class VMGeneric<A>
{
private A objVariable;
public VMGeneric(A localVariable)
{
objVariable = localVariable;
}
public String getNameOfGenericType()
{
return objVariable.getClass().getCanonicalName();
}
public static void main(String[] args)
{
VMGeneric<String> o1 = new VMGeneric<>("");
VMGeneric<Object> o2 = new VMGeneric<>(new Object());
System.out.println(o1.getNameOfGenericType());
System.out.println(o2.getNameOfGenericType());
}
}
关于Java:将泛型类型传递给另一个泛型类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22905914/