将通用参数传递给方法

时间:2019-04-19 11:18:46

标签: java generics generic-programming

我对Java泛型编程有些疑问。有什么方法可以检查传递给方法的参数的类型吗?我想比较调用该方法的实例的类型和传递给它的参数。

如果它们不相同,则应停止该方法的操作(一种保护)。

public void homeMatch(SportTeam<Type> visitors){

    if(the type of visitors and this-object are not the same){
         //do this
    }
    else{
         //do something different
    }
}

3 个答案:

答案 0 :(得分:3)

您无法在运行时对Type进行操作,因为编译器将其erased用作它。它仅在源代码中出于设计目的而存在。

Being more specific,此方法签名将被编译为

public void homeMatch(SportTeam visitors)

答案 1 :(得分:0)

如果您确实想进行检查,您可以做的是在函数参数中添加一个类参数。比将classParameter与它的类进行比较。这将起作用,因为访问者具有与typeClass相同的泛型类型。

public<Type> void homeMatch(Class<Type> typeClass, SportTeam<Type> visitors){
    if (typeClass.getClass() == this.getClass()){

    }
}

答案 2 :(得分:-3)

如果我正确理解,则必须使用instanceof。 像这样:

if (visitors instanceof Type) {
      // action
}
相关问题