我今天开始学习泛型,但这对我来说有点奇怪:
我有一个通用方法:
public<T> HashMap<String, T> getAllEntitySameType(T type) {
System.out.println(type.getClass());
HashMap<String, T> result = null;
if(type instanceof Project)
{
System.out.println(type.toString());
System.out.println("Yes, instance of Project;");
}
if(type instanceof String)
{
System.out.println(type.toString());
System.out.println("Yes, instance of String;");
}
this.getProjects();
return result;
}
而且我可以很容易地确定T类型的类别
Project<Double> project = new Project<Double>();
company2.getAllEntitySameType(project);
company2.getAllEntitySameType("TestString");
输出将是:
class Project
Yes, instance of Project;
class java.lang.String
TestString
Yes, instance of String;
我认为在泛型中我们不能使用实例。据我所知,有些事情还不完整。谢谢...
最佳答案
您可以使用 instanceof
检查对象的原始类型,例如Project
:
if (type instanceof Project)
或者对 Project
使用适当的泛型语法某种未知类型:
if (type instanceof Project<?>)
但你不能reify参数化类型,如 Project<Double>
与 instanceof
, 由于 type erasure :
if (type instanceof Project<Double>) //compile error
作为彼得·劳瑞 pointed out ,你也不能检查类型变量:
if (type instanceof T) //compile error
关于java - 在泛型方法中使用 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14219759/