日期:2014-05-20  浏览次数:20569 次

关于getClass的困惑

public class SE extends Date{
public static void main(String[] args) {
new SE().test();
}
void test(){
System.out.println(super.getClass().getSimpleName());
}
}
谁能分析下为什么输出是SE,而不是Date
getclass

------解决方案--------------------
getClass方法其实是从Object类继承类的,你不管调用谁的都是一样,所有的java类都不会去重写这个方法的。
Object类的getClass方法返回此 Object 的运行时类。
------解决方案--------------------
super.getClass().getSuperclass().getSimpleName()


getClass():Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.


getSuperclass():Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.




这样获取的是父类的名字。多看api。
------解决方案--------------------
引用:
super.getClass().getSuperclass().getSimpleName()


getClass():Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.


getSuperclass():Returns the Class representing the superclass of the entity (class, interface, primitive type or void) represented by this Class. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.




这样获取的是父类的名字。多看api。

遇到这种问题,看看API文档或源代码