Java generics

Why does the following look better than the old casting method?

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

vs.

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

+5
source share
5 answers

Another advantage of using an explicit type parameter would be to allow the implementation of a service method using Proxy(in this case MyObjshould be MyInterface). Without explicit type parameters, this would not be possible.

You can use Proxyunder covers for many reasons (testing for one)

+4
source

There is no guarantee that the non-generics version will return an object of type "MyObj", so you can get a ClassCastException.

+9
source

1 null, id someId MyObj. , MyObj.

2, instanceof (, ), ClassCastException, .

+6

, , , find(Class,String) , . , , . , , find String "someId". find String MyObj.

+3

This is no better. This is probably worse than in special circumstances. Only what you need is where the target will need to call newInstance () (etc.). In class methods, factory, etc.

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

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

All Articles