Reputation: 135
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?
Upvotes: 0
Views: 723
Reputation: 2540
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.
Upvotes: 0
Reputation: 73578
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.
Upvotes: 4