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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39657627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:20:10  来源:igfitidea点击:

How to pass generic Object as a Generic parameter on other method in java?

javagenerics

提问by lethanh

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 ? extends java.lang.Object ...

没有找到适合 doSomething(T) 的方法 T 不能转换为 ? 扩展 java.lang.Object ...

I think there might be a trick to avoid this, please help

我认为可能有一个技巧可以避免这种情况,请帮忙

采纳答案by ChenHuang

I think input.getClass()need be cast to Class<T>

我认为input.getClass()需要强制转换为Class<T>

public <S> void doOtherThing(S input){
      Something smt = Something.newInstance((Class<T>)input.getClass());
      smt.doSomething(input);
}

回答by Ivan

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){};
}

回答by Bastien

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);
    }
}