How to get class of generic type when there is no parameter of it?

后端 未结 5 857
星月不相逢
星月不相逢 2020-12-17 21:04

I just learned about this fine looking syntax

Collections.emptyList()

to get an empty List with elements which a

5条回答
  •  生来不讨喜
    2020-12-17 21:23

    I find out that there is one solution for getting Class from T:

    public class Action{
    }
    
    public Class getGenericType(Object action) throws ClassNotFoundException{
       Type type =
       ((ParameterizedType)action.getClass().getGenericSuperclass())
          .getActualTypeArguments()[0];
       String sType[] = type.toString().split(" ");
    
       if(sType.length != 2)
          throw new ClassNotFoundException();
    
       return Class.forName(sType[1]);
    }
    

    The usage of code above:

    Action myAction = new Action();
    
    getGenericType(myAction);
    

    I did not tested this with primitive types (int, byte, boolean).

    I think that it is not very fast, but you do not have to pass Class to constructor.

    EDIT:

    The usage above is not right, because generic superclass is not available for Action. Generic super class will be available only for inherited class like class ActionWithParam extends Action{}. This is reason why I changed my mind and now I suggest to pass class parameter to constructor, too. Thanks to newacct for correction.

提交回复
热议问题