简体   繁体   中英

Passing an generic parameter to the method

I have a little question about generic-programming in 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. 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. This would work because visitors have the same generic type as typeClass.

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

    }
}

if I understand correctly you must use instanceof . like this:

if (visitors instanceof Type) {
      // action
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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