[英]How to pass generic Object as a Generic parameter on other method in java?
I meet a trouble in using generic method 我遇到了使用泛型方法的麻烦
Compiled class: 编译类:
public class Something<T> {
public static Something newInstance(Class<T> type){};
public <T> void doSomething(T input){};
}
and my method is: 我的方法是:
public <S> void doOtherThing(S input){
Something smt = Something.newInstance(input.getClass());
smt.doSomething(input); // Error here
}
It got error at Compile time: 它在编译时遇到错误:
no suitable method found for doSomething(T) T cannot be converted to capture#1 of ?
没有找到适合doSomething(T)的方法T不能转换为捕获#1的? extends java.lang.Object ...
扩展java.lang.Object ...
I think there might be a trick to avoid this, please help 我想可能有一个窍门可以避免这种情况,请帮助
Pass the S class as an argument. 传递S类作为参数。
public class Something<T>
{
public static <T> Something<T> newInstance(Class<T> type)
{
return new Something<T>();
}
public void doSomething(T input){;}
public <S> void doOtherThing(Class<S> clazz, S input)
{
Something<S> smt = Something.newInstance(clazz);
smt.doSomething(input);
}
}
Anything like this? 有这样的吗? (generic type declaration thingy on our newInstance method)
(我们的newInstance方法的泛型类型声明)
public class Something<T> {
public static <T> Something<T> newInstance(Class<T> type){ return null; }
public <T> void doSomething(T input){};
}
I think input.getClass()
need be cast to Class<T>
我认为
input.getClass()
需要input.getClass()
为Class<T>
public <S> void doOtherThing(S input){
Something smt = Something.newInstance((Class<T>)input.getClass());
smt.doSomething(input);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.