简体   繁体   English

Java泛型

[英]Java generics

Why is the following seen as better than the old way of casting? 为什么以下看起来比旧的铸造方式更好?

MyObj obj = someService.find(MyObj.class, "someId");

vs.

MyObj obj = (MyObj) someService.find("someId");

无法保证非泛型版本将返回“MyObj”类型的对象,因此您可能会获得ClassCastException。

In case 1, most well-implemented services would be able to return null if there no object with id someId of type MyObj could be found. 在案例1中,如果没有找到id为someId类型为MyObj对象,则大多数实现良好的服务都能够返回null。 Moreover, the first case makes it possible for the service to have some specific logic particular to working with classes of type MyObj . 此外,第一种情况使得服务可以具有一些特定的逻辑,特别是对于MyObj类型的MyObj

In case 2, unless you use instanceof (avoid if possible), then you are risking a ugly ClassCastException which you would have to catch and handle. 在第2种情况下,除非你使用instanceof(尽可能避免),否则你冒着一个丑陋的ClassCastException ,你必须抓住并处理它。

Another advantage to using an explicit type parameter would be to allow the service method to be implemented using a Proxy (in this case MyObj would need to be MyInterface ). 使用显式类型参数的另一个好处是允许使用Proxy实现服务方法(在这种情况下, MyObj需要是MyInterface )。 Without explicit type parameters, this would not be possible. 没有明确的类型参数,这是不可能的。

You might use a Proxy under the covers for many reasons (testing for one) 出于多种原因,您可能会使用Proxy (测试一个)

One reason why first scenario is better is that the find(Class,String) method now has knowledge of what its return value is being assigned to. 第一种情况更好的一个原因是find(Class,String)方法现在知道它的返回值被分配给什么。 Therefore, it is now capable of doing any relevant casts internally instead of simply hoping the correct type was returned. 因此,它现在能够在内部执行任何相关的强制转换,而不是简单地希望返回正确的类型。 For example, suppose the find method locates a String object internally when called with "someId" . 例如,假设在使用"someId"调用时, find方法在内部定位String对象。 The find method may have a strategy for casting a String to a MyObj instance. find方法可能有一个将String转换为MyObj实例的策略。

It isn't better. 这不是更好。 Arguably its worse except in very specific circumstances. 可以说它更糟糕,除非在非常具体的情况下。 Only time you need that kind of thing is where the target is going to need to call newInstance() (etc) on the class object - factory methods and stuff. 只有你需要这种东西的时候,目标才需要在类对象上调用newInstance()(etc) - 工厂方法和东西。

If you want to save electrons, BTW, this will also work 如果你想节省电子,BTW,这也会起作用

MyObj obj = someService.find((Class<MyObj>) null, "someId");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM