简体   繁体   中英

how to call a generic parameterized method bounded JAVA?

I would like to know how I can call a bounded parameterized method.

For example, I have the following method :

  public static<R extends Reader & Runnable> R foo(R r) {
         r.run();
         return r;
  }

I would like to know how to call this method.

I try the following code :

    private static class Test extends Reader implements Runnable {
        ...........
    }

    private static <T extends extends & Runnable> T getInstance() {
        return (T) new Test(); 
    }

    public static void main(String[] args) {
        foo(getInstance());
    }

But I have the following exception :

Exception in thread "main" java.lang.ClassCastException: class ent.Main$Test cannot be cast to class java.lang.Runnable (ent.Main$Test is in unnamed module of loader 'app'; java.lang.Runnable is in module java.base of loader 'bootstrap')

And I can not find the solution.

Can someone have an idea?

Thank you in advance !

This:

private static <T extends Reader & Runnable> T getInstance() {

means that the method can return something that can be cast to any class which both extends Reader and implements Runnable . However, there is only one such value that you can return safely from this:

return null;

Anything else could result in a ClassCastException . In particular, return new Test(); will only succeed if you happen to have invoked is in a context expecting to receive a Test .

In general, you can't safely return a non-null T from a method if T does not feature in the formal parameters. See the documentation of Error Prone's TypeParameterUnusedInFormals check for more detail.

If you want to return an instance of Test from getInstance() , drop the generics and make the return type Test .

private static Test getInstance() {
    return new Test(); 
}

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