本文介绍了Class< T>的Java泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一张地图:

 地图< String,Class> format = new HashMap< String,Class>(); 

我会像这样添加元素:

  format.put(Vendor Number,Integer.class); 
format.put(Vendor Dispatch,Date.class);
....

我有一个通用方法,如下所示:

  public static< T> T verifyType(String name,Class< T> type){
if(type == Integer.class){
return type.cast(new Integer(Integer.parseInt(name)));
}
......
返回null;
}

现在这段代码很好用,没有编译器问题:

  Integer i = verifyType(100,Integer.class); 

但是,当我试试这个时:

  Integer i = verifyType(100,format.get(Vendor Number)); 



类型= Integer.class
整数i = verifyType(100,type);

编译器向我显示以下警告:
类型安全性:未经检查的调用verifyType(String,Class)通用方法verifyType(String,Class)



这让我感到困惑...请帮助...



 类型类型= Integer.class 
整数i = verifyType(100,type);

 类<整数> type = Integer.class 
Integer i = verifyType(100,type);

只要将类型声明为'Class',就会失去泛型参数和verifyType )方法无法推断出类,因此未经检查的警告。



这个问题:

 地图< String,Class> format = new HashMap< String,Class>(); 
format.put(Vendor Number,Integer.class);
format.put(Vendor Dispatch,Date.class);
Integer i = verifyType(100,format.get(Vendor Number));

由于类型删除而无法真正解决。编译器无法根据运行时消除的通用参数来推断该类型。这是因为Java泛型只不过是用于投射的镜像。


So I have a map:

Map<String, Class> format = new HashMap<String, Class>();

And I would add elements to it like this:

format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
....

I have a generic method as follows:

public static <T> T verifyType(String name, Class<T> type) {
    if (type == Integer.class) {
        return type.cast(new Integer(Integer.parseInt(name)));
    }
             ......
    return null;
}

Now this piece of code works great with no compiler issues:

Integer i = verifyType("100",Integer.class);

But, when I try this:

    Integer i = verifyType("100",format.get("Vendor Number"));

OR

    Class type = Integer.class
    Integer i = verifyType("100",type);

Compiler shows me this warning:Type safety: Unchecked invocation verifyType(String,Class) of the generic method verifyType(String, Class)

That leaves me puzzled... please help...

解决方案

Change:

Class type = Integer.class
Integer i = verifyType("100",type);

to

Class<Integer> type = Integer.class
Integer i = verifyType("100",type);

By only declaring the type as 'Class', you're losing the generic parameter and the verifyType() method can't infer the class, thus the unchecked warning.

This problem:

Map<String, Class> format = new HashMap<String, Class>();
format.put("Vendor Number", Integer.class);
format.put("Vendor Dispatch", Date.class);
Integer i = verifyType("100",format.get("Vendor Number"));

can't really be solved due to type erasure. The compiler can't infer the type based on a generic parameter that is gone by runtime. This is because Java generics are little more than smoke and mirrors for casting.

这篇关于Class&lt; T&gt;的Java泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:22