我有一个通用基类:
public class BaseLabel<T> extends JXLabel {
private static final long serialVersionUID = 1L;
public BaseLabel() {
System.out.println(T.class.getClass().getName()); //error
}
}
和子类:
public class ChildLabel extends BaseLabel<ChildLabel> {
private static final long serialVersionUID = 2L;
public ChildLabel() {
}
}
我遇到编译错误。
有什么方法可以从 BaseClass 的构造函数中获取实际的类名。在这里,我指的是实际类,我将实例化它。
例如我正在实例化 ChildClass,ChildClass clz = new ChildClass()
;
然后 println()
将打印 package.ChildClass
。
提前致谢。
编译错误为:
cannot select from a type variable System.out.println(T.class.getClass().getSimpleName());
如果我从 abstract BaseClass
的构造函数中调用 this.getClass.getSimpleName()
。它正在打印 ChildClass
。
为什么?
是不是因为我正在实例化 ChildClass
所以 this 指向 ChildClass
的对象。
最佳答案
丑陋?是的
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();
}
}
子类
import java.lang.reflect.ParameterizedType;
public class ChildClass extends GenericClass<Foo> {
public ChildClass() {
System.out.println(((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]); //output: class Foo
}
}
关于java - 通用类 - getClass().getName(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416968/