Java Generic Class - Determine Type

前端 未结 8 2124
野性不改
野性不改 2020-11-27 12:48

If I am creating a java class to be generic, such as:

public class Foo

How can one determine internally to that class, what \'T\

8条回答
  •  不知归路
    2020-11-27 13:31

    I've used a similar solution to what he explains here for a few projects and found it pretty useful.

    http://blog.xebia.com/2009/02/07/acessing-generic-types-at-runtime-in-java/

    The jist of it is using the following:

     public Class returnedClass() {
         ParameterizedType parameterizedType = (ParameterizedType)getClass()
                                                     .getGenericSuperclass();
         return (Class) parameterizedType.getActualTypeArguments()[0];
    }
    

提交回复
热议问题