将通用参数传递给方法
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
进行操作,因为它是由编译器 erased 操作的。它仅出于设计目的存在于源代码中。
Being more specific,此方法签名将被编译为类似
的内容
public void homeMatch(SportTeam visitors)
如果我理解正确的话,你必须使用 instanceof 。
像这样:
if (visitors instanceof Type) {
// action
}
如果你真的想进行检查,你可以做的是向函数参数添加一个 class 参数。比 class 参数与此的 class 比较。这会起作用,因为访问者具有与 typeClass 相同的通用类型。
public<Type> void homeMatch(Class<Type> typeClass, SportTeam<Type> visitors){
if (typeClass.getClass() == this.getClass()){
}
}
我对 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
进行操作,因为它是由编译器 erased 操作的。它仅出于设计目的存在于源代码中。
Being more specific,此方法签名将被编译为类似
的内容public void homeMatch(SportTeam visitors)
如果我理解正确的话,你必须使用 instanceof 。 像这样:
if (visitors instanceof Type) {
// action
}
如果你真的想进行检查,你可以做的是向函数参数添加一个 class 参数。比 class 参数与此的 class 比较。这会起作用,因为访问者具有与 typeClass 相同的通用类型。
public<Type> void homeMatch(Class<Type> typeClass, SportTeam<Type> visitors){
if (typeClass.getClass() == this.getClass()){
}
}