How to pass a shared object as a common parameter to another method in java?

I encounter a problem using a generic method

Compiled class:

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

and my method:

 public <S> void doOtherThing(S input){ Something smt = Something.newInstance(input.getClass()); smt.doSomething(input); // Error here } 

An error occurred at compile time:

there is no suitable method for doSomething (T) T cannot be converted to capture # 1 from? extends java.lang.Object ...

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

+7
java generics
source share
3 answers

I think input.getClass() needs to be dropped to Class<T>

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

Pass class S 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); } } 
+4
source share

Anything like this? (declaration of a universal type by our newInstance method)

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

All Articles