Reputation: 15733
create a interface(using template):
package util.filter;
public interface Filter<INPUT,OUTPUT> {
public OUTPUT filter(INPUT mes);
}
and an implemented class (only for test):
package util.filter;
public static class TestImplFilter implements Filter<Integer,String>{
public String filter(Integer i){
return "Hello World!";
}
}
I can using this code to test:
Filter<Integer,String> f=new TestImplFilter();
System.out.println(f.filter(123));
//output: Hello World!
now,I want create a static method,
using impl class path (util.filter.TestImplFilter
) as an argument,
and INPUT as second argument, and return a OUTPUT.
so, I writed follow code:
private static Object createInstance(String classPath) {
try {
Class<?> tClass = Class.forName(classPath);
if (tClass != null) {
return tClass.newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public final static Filter<?,?> getFilter(String path){
return (Filter<?,?>)createInstance(path);
}
//my problem in here:
public final static OUTPUT filter(String path,INPUT mes){
Filter<?,?> filter = (Filter<?, ?>) createInstance(path);
return filter.filter(mes);
}
my problem in static method filter(String path,INPUT mes)
, this code is error.
how can I fix it and implement this method?
thanks for help :)
Upvotes: 0
Views: 411
Reputation: 120831
my mistake, I mashed the order, now it is correct
You can specifiy generics for static methods too. To do that, add the gereric template information ahead of the return parameter:
public final static<INPUT,OUTPUT> OUTPUT filter(String path,INPUT mes){
then it will compile.
public class Test {
private static Object createInstance(String classPath) {
try {
Class<?> tClass = Class.forName(classPath);
if (tClass != null) {
return tClass.newInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
public final static <INPUT, OUTPUT> Filter<INPUT, OUTPUT> getFilter(String path) {
return (Filter<INPUT, OUTPUT>) createInstance(path);
}
public final static <INPUT, OUTPUT> OUTPUT filter(String path, INPUT mes) {
Filter<INPUT, OUTPUT> filter = getFilter(path);
return filter.filter(mes);
}
}
Upvotes: 2