如何将通用对象作为通用参数传递给java中的其他方法?

let*_*anh 8 java generics

我遇到了使用泛型方法的麻烦

编译类:

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 ...

我想可能有一个窍门可以避免这种情况,请帮助

Bas*_*ien 7

传递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)

  • 由于原始类型和未经检查的铸造,这是不安全的。 (4认同)