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
A Generic class can have muliple type parameters.
Which of these type parameters is used for a generic class to return and accept any type of object? Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.
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);
}
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With