Java generic function: how to return Generic type

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

Here\'s a Java generic pattern:

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


        
6条回答
  •  旧时难觅i
    2020-12-16 16:22

    Well,. here's an ugly (partial) solution. You can't generically paramaterize a generic param, so you can't write

    public > T getResultData ...
    

    but you can return a parameterized collection, e.g. for a set

    public < T extends Set< U >, U > T getResultData( Class< T > resultClass, Class< U > paramClass ) throws IllegalAccessException, InstantiationException {
            return resultClass.newInstance();
        }
    

    where you could get rid of the U-param if it existed in the class signature.

提交回复
热议问题