Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a generic Interface with concrete implementation in java

I have a generic Interface which is implemented by a class, that I want to return in a generic method. Interface:

public interface IWorker<T extends Object, K extends Object> {  
public K doWork(T o);
}

Implementation:

public class WorkerImpl implements IWorker<String, List<Serializable>>
{
   @Override
   public List<Serializable> doWork(String s)
   {
       return ...
   }
}

ActionCoordinator Interface for the generic method returning the implementation:

public interface IActionCoordinator
{
    public <T extends Serializable, K extends Serializable> IWorker<T, K> getAction(T  request);
}

ActionCoordinator implementation:

public class ActionCoordinatorImpl implements IActionCoordinator
{
    @Override
    public <T extends Serializable, K extends Serializable> IWorker<T, K> getAction(final T requ)
    {
        return (IWorker<T,K>)new WorkerImpl();
    }
}

Problem: In eclipse this will work, but doing a maven build with the JDK 1.6.0_35 doesn't and says "inconvertible types". I can get around with that:

public class ActionCoordinatorImpl implements IActionCoordinator
{
    @Override
     public <T extends Serializable, K extends Serializable> IWorker<T, K> getAction(final T requ)
    {
        Object temp = new WorkerImpl();
        return (IWorker<T,K>)temp;
    }
}

But that it's not supposed to be, that wouldn't be type-safe at all.

Some ideas would be nice. Thanks in advance...

EDIT: What works for me now is the following: I changed all the generic Ts and Ks to be Serializable. Thats all what I needed to restrict the WorkerImpl to be. the actual caller still needs an IWorker<T,K> but IWorker<Serializable,Serializable> fits and works...thanks everyone, but I still wonder why eclipse is not saying anything...

like image 268
peatle_pp Avatar asked Mar 31 '26 14:03

peatle_pp


1 Answers

The problem is not that maven won't compile, it's that Eclipse isn't complaining about an unsafe cast: You probably have an option turned off in your Eclipse preferences and are doing a strict compile in maven.

Your WorkerImpl is unsuitable to return from your factory method in ActionCoordinatorImpl, because there's no guarantee that the Serializable passed to its doWork() method will be a String - it just has to be any Serializable.


Also, you could simplify your code by changing IWorker from

public interface IWorker<T extends Object, K extends Object>

to

public interface IWorker<T, K>

Since they are equivalent (everything extends Object)

like image 169
Bohemian Avatar answered Apr 03 '26 05:04

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!