Java generic function: how to return Generic type

后端 未结 6 1936
春和景丽
春和景丽 2020-12-16 15:46

Here\'s a Java generic pattern:

public  T getResultData(Class resultClass, other_args) { 
   ...
   return resultClass.cast(T-thing);
}
         


        
6条回答
  •  攒了一身酷
    2020-12-16 16:08

    So if I understood correctly what you really trying to do is (illegal pseudo-syntax):

    public  T getResultData(Class> resultClass, other_args) { 
      ...
      return resultClass.cast(T-thing);
    }
    

    You can't because you can't further parameterize generic type T. Messing about with java.lang.reflect.* won't help:

    1. There is no such thing as Class> and thus no way to dynamically create its instance.
    2. There is no way to actually declare the method in question as returning T

提交回复
热议问题