How do I get a class instance of generic type T?

前端 未结 22 1575
猫巷女王i
猫巷女王i 2020-11-21 11:03

I have a generics class, Foo. In a method of Foo, I want to get the class instance of type T, but I just can\'t call T.

22条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 11:42

    Here is a working solution:

    @SuppressWarnings("unchecked")
    private Class getGenericTypeClass() {
        try {
            String className = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0].getTypeName();
            Class clazz = Class.forName(className);
            return (Class) clazz;
        } catch (Exception e) {
            throw new IllegalStateException("Class is not parametrized with generic type!!! Please use extends <> ");
        }
    } 
    

    NOTES: Can be used only as superclass

    1. Has to be extended with typed class (Child extends Generic)

    OR

    1. Has to be created as anonymous implementation (new Generic() {};)

提交回复
热议问题