How to replace these type-specific methods with a single method that uses Java Generics?

Just copying what you've done earlier , that should work. You probably don't even need the Class parameter.

Up vote 0 down vote favorite 1 share g+ share fb share tw.

I'm trying to replace these type-specific save methods with a generic approach: public Apple save(Apple apple) { pm. MakePersistent(apple); pm.close(); return apple; } public Orange save(Orange orange) { pm. MakePersistent(orange); pm.close(); return orange; } This is what I've come up with but I'm having trouble figuring out how to cast the return value: public T save(Object fruit, Class model) { pm.

MakePersistent(fruit); return result; } java generics link|improve this question asked Aug 9 '11 at 22:42Cantica1.

Public T save(T fruit) { pm. MakePersistent(fruit); pm.close(); return fruit; } Just copying what you've done earlier , that should work. You probably don't even need the Class parameter.

Argh, you got it right haha – Jean-Bernard Pellerin Aug 9 '11 at 22:47.

The invoker of the method already has a reference to the fruit object. Public void save ( Fruit fruit ) { pm. MakePersistent(fruit); pm.close(); }.

Public T save(T fruit) { pm. MakePersistent(fruit); pm.close(); return fruit; //Is this needed? } The above will do it for you but if the makePersistent() method takes any type of fruit anyway there's really no need in this example.

Of course, if the real use case is somewhat different you may need it.

The above assumes the makePersistent method takes any type of fruit but gives it any type of Object. It will not work. Consider: String s = " String t = save ( s ) ; – emory Aug 10 '11 at 0:08 @emory looking at the example I was actually assuming it did take any type of object, but I've altered the example to just take fruit now.

– berry120 Aug 10 '11 at 9:00.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions