[英]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
}
}
如果你真的想要进行检查,你可以做的是在函数参数中添加一个类参数。 比较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.