简体   繁体   中英

In Java, how to get all possible return types?

In Java, a method could be defined as following:

Object m(boolean b) {
    if (b) {
        return "123";
    } else {
        return new Integer(123);
    }
}

In this case, the return value of m could be either String or Integer in runtime. So is there any way to get all possible run time return types of a method in static time?

For this particular method, yes. Just call it with true and false and check the return value with getClass() . For a general case, no.

Generally you wouldn't need to either. Thanks to Java's strong typing and generics, the type of the return value should never be a huge surprise.

Returning multiple different types as shown in your example should be avoided, and in cases where it's useful/necessary (such as factory pattern) it should be irrelevant to the caller.

If you know the implementation of the method, yes. You know all the types it could return because you can read the code and tell for yourself what they are.

But, programmatically? For any method, in general? No, you can't do that, not at run-time. This is why it's very important to write good, sensical method signatures with meaningful return-types. Returning Object is seldom the best idea. When you say that your method returns Object , the contract of that method is that literally anything is allowed to come out of it. There's nothing wrong with that, but that's the most specific thing you can say about a method if all you know is its signature.

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