简体   繁体   English

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

[英]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.

相关问题 如何将通用类作为方法的通用参数传递 - How to pass generic class as a generic parameter of method 如何将一类的arraylist对象传递给以对象为参数的通用方法 - how to pass a arraylist object of one class to generic method which is having object as its parameter in java 将泛型作为方法的参数 - Pass Generic as parameter of method 如何传递一个方法作为其他方法的参数,但使最后一个方法在其签名上具有泛型作为参数? - how to pass a method as parameter of other method but making the last method have a generic as parameter on its signature? 一个带有泛型参数的java方法 - 为什么我不能传递一个带有泛型参数的对象,该参数是方法参数的子类? - A java method that has a generic parameter- why can't I pass an object with a generic parameter that is a subclass of the method arguments? 如何将通用参数传递给方法? - How do I pass a generic parameter to a method? 如何通过泛型方法引用作为参数? - How to pass generic method reference as parameter? java 如何确定,当一个方法具有泛型类型参数而另一个具有非泛型参数时,将调用哪个重载方法? - How does java determine, which overloaded method will call, when one method with generic type parameter and other with non generic parameter? 如何“投射”到通用对象并使用通用参数执行方法 - How to 'cast' to a generic object and execute method with generic parameter 在方法参数中传递通用 class - Pass a generic class in method parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM