Java泛型参数不能应用于特定类型
public class Demo {
public String work(String s) {
return s;
}
public <T> T Test(T t) {
// common work to do !!
// .....
// spec work to do
T result = work(t);
return result;
}
}
测试()具有一些共同工作的第一做,然后相对于具体的工作,以不同类型的T. 的以上代码导致编译器错误,我怎样才能做这个 ? 非常感谢!Java泛型参数不能应用于特定类型
另一种方法是使用反射。请注意,反射是一个强大的工具,但它也是有代价的进行测量,看看这是否是一个可行的解决方案是你的具体情况(性能):
public class Demo {
private String work(String s) {
return s.toUpperCase();
}
private Boolean work(Boolean b) {
return !b;
}
public <T> T test(T t) {
// common work to do !!
// .....
// Now look-up "work" method for type T. Invoke if defined.
T result = null;
try {
Class<T> tType = (Class<T>) t.getClass();
Method work = Demo.class.getDeclaredMethod("work", tType);
if (work.getReturnType() != tType) {
throw new NoSuchMethodException("No `work` method for type: " + tType);
}
result = (T) work.invoke(this, t);
} catch (NoSuchMethodException e) {
// NOOP - or whatever.
} catch (IllegalAccessException | InvocationTargetException e) {
// Method invocation failed. Handle properly.
e.printStackTrace();
}
return result;
}
}
谢谢,这可以做我想要的! – TAW8750
有很多事情可能导致你的代码不能在这里编译;除了';'之外,你正在从无效方法中返回一些东西。请发布您也面临的编译器错误,这会让潜在的响应者更清楚。
对不起,这是一个简单的一块来演示该问题 的主要错误是参数不匹配 它说: 工作()需要参数(如String),但通过一件T (generic type) – TAW8750
什么你可以可能逃脱是创建T
类型映射到(unary?)function。然后,在test
方法中,您可以查找类型T
。如果一个函数是registerede,适用于:
public class Demo {
private static final Map<Class<?>, UnaryOperator<?>> typeFuncs = new HashMap<>();
static {{
addTypeFunc(String.class, (String s) -> s); // Anonymous function.
addTypeFunc(Integer.class, Demo::workInteger); // Function reference.
}}
private static <T> void addTypeFunc(Class<T> type, UnaryOperator<T> func) {
typeFuncs.put(type, func);
}
private static Integer workInteger(Integer i) {
return i;
}
public <T> T test(T t) {
// common work to do !!
// .....
T result = null;
UnaryOperator<T> operator = (UnaryOperator<T>) typeFuncs.get(t.getClass());
if (operator != null) {
result = operator.apply(t);
}
return result;
}
}
请注意,test
投(UnaryOperator<T>)
仅仅是安全的,因为我们在typeFuncs
地图键和值类型之间的关系的总量控制。
你不能做这样的在Java中任何东西。在编译时决定选择哪种方法的重载,而不是运行时。 –
我该如何实现? Test()需要处理不同的参数类型,并且需要先在该函数中完成一些常见工作,我只是想将通用部分提取到Test()中。 – TAW8750
将公共部分拉出到一个单独的方法,并有多个测试重载,调用该单独的方法,然后执行专门的工作。 –