Cantica
Cantica

Reputation: 1

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

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> T save(Object fruit, Class<T> model)
{
    pm.makePersistent(fruit);
    return result;
}

Upvotes: 0

Views: 114

Answers (3)

Michael Berry
Michael Berry

Reputation: 72254

Is there really a need for generics with the above example?

public <T extends Fruit> 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.

Upvotes: 2

emory
emory

Reputation: 10891

Why do you need generics?

Why do you need to return the fruit? The invoker of the method already has a reference to the fruit object.

public void save ( Fruit fruit )
{
     pm.makePersistent(fruit);
     pm.close();
}

Upvotes: 2

Kal
Kal

Reputation: 24910

public <T> 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.

Upvotes: 3

Related Questions