我遇到了使用泛型方法的麻烦
编译类:
public class Something<T> {
public static Something newInstance(Class<T> type){};
public <T> void doSomething(T input){};
}
Run Code Online (Sandbox Code Playgroud)
我的方法是:
public <S> void doOtherThing(S input){
Something smt = Something.newInstance(input.getClass());
smt.doSomething(input); // Error here
}
Run Code Online (Sandbox Code Playgroud)
它在编译时遇到错误:
没有找到适合doSomething(T)的方法T不能转换为捕获#1的?扩展java.lang.Object ...
我想可能有一个窍门可以避免这种情况,请帮助
传递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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我认为input.getClass()需要强制转换为Class<T>
public <S> void doOtherThing(S input){
Something smt = Something.newInstance((Class<T>)input.getClass());
smt.doSomething(input);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35044 次 |
| 最近记录: |