读书人

关于getClass的疑惑

发布时间: 2013-11-09 17:06:34 作者: rapoo

关于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文档或源代码

读书人网 >J2SE开发

热点推荐