简体   繁体   English

将泛型参数传递给方法

[英]Passing an generic parameter to the method

I have a little question about generic-programming in Java. 我对Java中的泛型编程有一点疑问。 Is there any way to check the type of the parameter passed to the method? 有没有办法检查传递给方法的参数的类型? I would like to compare the types of an instance which calls the method, and the parameter passed to it. 我想比较一个调用方法的实例的类型,以及传递给它的参数。

If they are not the same, the action of the method should be stopped (kind of protection). 如果它们不相同,则应停止该方法的动作(保护种类)。

public void homeMatch(SportTeam<Type> visitors){

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

You cannot operate with Type at runtime as it is erased by the compiler. 您无法在运行时使用Type进行操作,因为编译器会将其删除 It only exists at the source code for design purposes. 它仅存在于源代码中以用于设计目的。

Being more specific , this method signature will be compiled to something like 更具体地说 ,这个方法签名将编译成类似的东西

public void homeMatch(SportTeam visitors)

What you could do, if you really want to have that check, is to add a class parameter to the functions arguments. 如果你真的想要进行检查,你可以做的是在函数参数中添加一个类参数。 Than compare the classParameter with the class of this. 比较classParameter和这个类。 This would work because visitors have the same generic type as typeClass. 这可以工作,因为访问者具有与typeClass相同的泛型类型。

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

    }
}

if I understand correctly you must use instanceof . 如果我理解正确,你必须使用instanceof。 like this: 像这样:

if (visitors instanceof Type) {
      // action
}

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

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