lethanh
lethanh

Reputation: 342

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

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

Upvotes: 14

Views: 85911

Answers (3)

Bastien
Bastien

Reputation: 658

Pass the S class as an argument.

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

Upvotes: 8

ChenHuang
ChenHuang

Reputation: 392

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

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

Upvotes: 7

Ivan
Ivan

Reputation: 3836

Anything like this? (generic type declaration thingy on our newInstance method)

public class Something<T> {
   public static <T> Something<T> newInstance(Class<T> type){ return null; }
   public <T> void doSomething(T input){};
}

Upvotes: 1

Related Questions