I have an interface as follows,
public interface MethodExecutor {
<T> List<T> execute(List<?> facts, Class<T> type) throws Exception;
}
Also, I have a generic implementation like below,
public class DefaultMetodExecutor implements MethodExecutor {
public <T> List<T> execute(List<?> facts, Class<T> type) throws Exception
{
List<T> result = null;
//some implementation
return result;
}
}
Upto this there is no compilation issues,
But a specific implementation of this interface fails to compile, The one which shown below.
public class SpecificMetodExecutor implements MethodExecutor {
public <Model1> List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception
{
List<Model1> result = null;
//some implementation specific to Model1 and Model2
return result;
}
}
How can I implement this interface for some of the defined objects? Do I need to go for class level generics?
You need to make T
a class type parameter, not a method type parameter. You can't override a generic method with a non-generic method.
public interface MethodExecutor<T> {
List<T> execute(List<?> facts, Class<T> type) throws Exception;
}
public class DefaultMethodExecutor implements MethodExecutor<Model1> {
public List<Model1> execute(List<?> facts, Class<Model1> type) throws Exception
{
//...
}
}
If the element type of facts
should be configurable for a specific implementation, you need to make that a parameter too.
public interface MethodExecutor<T, F> {
List<T> execute(List<? extends F> facts, Class<T> type) throws Exception;
}
You need to move your generic parameter types from method declaration to interface declaration, so you can parametrize specific implementations:
public interface MethodExecutor<T> {
List<T> execute(List<?> facts, Class<T> type) throws Exception;
}
public class SpecificMetodExecutor implements MethodExecutor<Model1> {
public List<Model1> execute(List<Model2> facts, Class<Model1> type) throws Exception {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With