简体   繁体   中英

Java Generics AnyType, how do I allow any method to be called?

Given:

public<?> void methodName(? input){
  var something = ?.GetItNow();
}

We have a ton of classes that were auto-generated from WSDL. Almost all of them have the same methods, but there is no way to have them implement an interface for those same methods. Assume all these different classes have a method named GetItNow(). My question is how do I set up a Generic method to allow the code above to work?

When using the "?" do I have to always use the "extends" key-word? If so how do I extend any object so I don't see compile errors that "method doesn't exist.

Note the code above is for illustration purposes only and does not do anything (yet).

You could use reflection to access the method, provided the name is known beforehand.

public void methodName(Object input){
    try{
        Method method = input.getClass().getMethod("GetItNow");
        RETURN_TYPE returnValue = (RETURN_TYPE)method.invoke(input);
    }catch(Exception e){
        throw new RuntimeException("Error while invoking method",e);
    }
}

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