Joshua
Joshua

Reputation: 26742

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");

Upvotes: 5

Views: 336

Answers (5)

PaulMurrayCbr
PaulMurrayCbr

Reputation: 1260

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.

If you want to save electrons, BTW, this will also work

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

Upvotes: 0

oxbow_lakes
oxbow_lakes

Reputation: 134330

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). Without explicit type parameters, this would not be possible.

You might use a Proxy under the covers for many reasons (testing for one)

Upvotes: 4

Adam Paynter
Adam Paynter

Reputation: 46938

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. 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". The find method may have a strategy for casting a String to a MyObj instance.

Upvotes: 3

Il-Bhima
Il-Bhima

Reputation: 10880

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. Moreover, the first case makes it possible for the service to have some specific logic particular to working with classes of type 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.

Upvotes: 6

Tim Frey
Tim Frey

Reputation: 9941

There's no guarantee that the non-generics version will return an object of type 'MyObj', so you might get a ClassCastException.

Upvotes: 9

Related Questions