在java中,如何将泛型对象作为泛型参数传递给其他方法?

在java中,如何将泛型对象作为泛型参数传递给其他方法?,java,generics,Java,Generics,我在使用泛型方法时遇到了麻烦 编译类: public class Something<T> { public static Something newInstance(Class<T> type){}; public <T> void doSomething(T input){}; } 公共类{ 公共静态实例(类类型){}; 公共无效剂量测定(T输入){}; } 我的方法是: public <S> void doOtherThing

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

编译类:

public class Something<T> {
   public static Something newInstance(Class<T> type){};
   public <T> void doSomething(T input){};
}
公共类{
公共静态实例(类类型){};
公共无效剂量测定(T输入){};
}
我的方法是:

public <S> void doOtherThing(S input){
      Something smt = Something.newInstance(input.getClass());
      smt.doSomething(input); // Error here
}
public void doOtherThing(S输入){
Something smt=Something.newInstance(input.getClass());
smt.doSomething(输入);//此处出错
}
它在编译时出错:

未找到适用于剂量测定的方法(T)T无法转换为 捕获#1个?扩展java.lang.Object

我想可能有一个技巧可以避免这种情况,请帮助我做类似的事情?(newInstance方法上的泛型类型声明)

公共类{
公共静态实例(类类型){return null;}
公共无效剂量测定(T输入){};
}

我认为
input.getClass()
需要转换为
Class

public void doOtherThing(S输入){
Something smt=Something.newInstance((Class)input.getClass());
smt.剂量测量(输入);
}

将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);
    }
}
公共类
{
公共静态实例(类类型)
{
返回新事物();
}
公共void doSomething(T输入){;}
公共虚空涂鸦(类clazz,S输入)
{
Something smt=Something.newInstance(clazz);
smt.剂量测量(输入);
}
}

Nope,它可以与非泛型变量(如字符串)一起工作。这是不安全的,因为原始类型和未经检查的强制转换。但如果不是静态的,则实际上doOtherThing是相当无用的。基本上,它只是创建一个Something实例并应用doSomething,使用泛型类型s而不是来自同一类s的T.2参数来使用泛型,这是避免未检查强制类型转换警告的一种略微冗余的方法。实际上,在这个示例中,
类类型
未使用,所以您甚至不需要它。有趣。
Something
返回类型中的
T
引用的是推断为泛型的参数还是词法类的泛型?这里有很多问题。首先有两个独立的
T
s
doSomething
T
与类
Something
T
不同,因为
doSomething
是一个声明自己的
T
的通用方法。您应该以不同的方式命名这两个变量,因为它们彼此不相关。然后,
doSomething
只使用
T
一次作为参数类型,并且
T
是无界的,这意味着它接受任何内容,因此它相当于
public void doSomething(对象输入){}
T
无效。与
doOtherThing
相同——它相当于
public void doOtherThing(对象输入)
public <S> void doOtherThing(S input){
      Something smt = Something.newInstance((Class<T>)input.getClass());
      smt.doSomething(input);
}
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);
    }
}