泛型类 - getClass().getName()

Tap*_*ose 3 java generics

我有一个通用的基类:

public class BaseLabel<T> extends JXLabel {
    private static final long serialVersionUID = 1L;

    public BaseLabel() {
        System.out.println(T.class.getClass().getName()); //error
    }       
}
Run Code Online (Sandbox Code Playgroud)

和儿童班:

public class ChildLabel extends BaseLabel<ChildLabel> {
    private static final long serialVersionUID = 2L;

    public ChildLabel() {

    }       
}
Run Code Online (Sandbox Code Playgroud)

我收到编译错误.

有没有办法从BaseClass的构造函数中获取实际的类名.在这里,通过实际的类我指的是那个我要实例化的类.

例如,我正在实例化ChildClass , ChildClass clz = new ChildClass();

然后那println()将打印package.ChildClass.

提前致谢.


编译错误是:

cannot select from a type variable System.out.println(T.class.getClass().getSimpleName());
Run Code Online (Sandbox Code Playgroud)

如果我this.getClass.getSimpleName()abstract BaseClass构造函数调用.它正在印刷ChildClass.

为什么?

它是由于,因为我实例化,ChildClass所以这指向了ChildClass对象.

Vin*_*lle 7

丑陋?是

import java.lang.reflect.ParameterizedType;


public class GenericClass<T> {

    public GenericClass() {
        System.out.println(getClass().getGenericSuperclass()); //output: GenericClass<Foo>
        System.out.println(((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]); //output: class Foo
    }

    public static void main(String[] args) {
        new ChildClass();
    }

}
Run Code Online (Sandbox Code Playgroud)

儿童班

import java.lang.reflect.ParameterizedType;


public class ChildClass extends GenericClass<Foo> {

    public ChildClass() {
        System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); //output: class Foo
    }

}
Run Code Online (Sandbox Code Playgroud)