繁体   English   中英

将泛型参数传递给方法

[英]Passing an generic parameter to the method

我对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
    }
}

您无法在运行时使用Type进行操作,因为编译器会将其删除 它仅存在于源代码中以用于设计目的。

更具体地说 ,这个方法签名将编译成类似的东西

public void homeMatch(SportTeam visitors)

如果你真的想要进行检查,你可以做的是在函数参数中添加一个类参数。 比较classParameter和这个类。 这可以工作,因为访问者具有与typeClass相同的泛型类型。

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

    }
}

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

if (visitors instanceof Type) {
      // action
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM