[英]In Java, how to get all possible return types?
In Java, a method could be defined as following: 在Java中,方法可以定义如下:
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. 在这种情况下,m的返回值在运行时可以是String或Integer。 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()
. 只需使用
true
和false
调用它,然后使用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.
得益于Java强大的类型和泛型,返回值的类型永远不会让人感到意外。
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. 返回
Object
很少是最好的主意。 When you say that your method returns Object
, the contract of that method is that literally anything is allowed to come out of it. 当您说您的方法返回
Object
,该方法的约定是字面上允许出现的任何内容。 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. 没什么错,但是如果您只知道方法的签名,那么这就是您可以说的关于方法的最具体的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.