Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass generic Object as a Generic parameter on other method in java?

Tags:

java

generics

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

like image 798
lethanh Avatar asked Sep 23 '16 09:09

lethanh


People also ask

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

Which parameters is used for a generic class to return and accept any type of object?

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.

How do you declare a generic method How do you invoke a generic method?

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.

Does Java allow you to instantiate generic objects?

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.


2 Answers

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);
    }
}
like image 106
Bastien Avatar answered Nov 15 '22 16:11

Bastien


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);
}
like image 26
ChenHuang Avatar answered Nov 15 '22 16:11

ChenHuang