5

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

1
  • 1
    Who says that this is better? Commented Feb 23, 2009 at 19:44

5 Answers 5

9

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

Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

4

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)

Comments

3

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.