Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics

Tags:

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

like image 263
Joshua Avatar asked Feb 23 '09 19:02

Joshua


2 Answers

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

like image 121
Outlaw Programmer Avatar answered Sep 27 '22 23:09

Outlaw Programmer


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.

like image 32
Il-Bhima Avatar answered Sep 28 '22 00:09

Il-Bhima