Discuss / Java / 有关getClass()的问题

有关getClass()的问题

Topic source

年年有于

#1 Created at ... [Delete] [Delete and Lock User]

由于Java类的动态特性,子类获取的log字段实际上相当于LogFactory.getLog(Student.class),但却是从父类继承而来,并且无需改动代码。

为什么 getClass() 不是object执行的?

我知道结果是子类执行的getClass,但是不知道其原理;

类比于toString,如果子类没重写那就是Object的toString,也就是打印hashCode;

子类未重写getClass,那执行的为什么不是Object的getClass.谁能解释一下吗?

呜哇

#2 Created at ... [Delete] [Delete and Lock User]

getClass 是 nativate 本地方法,具体作用可以看注释(来自 JDK1.8的注释)

* Returns the runtime class of this {@code Object}. The returned* {@code Class} object is the object that is locked by {@code* static synchronized} methods of the represented class.** <p><b>The actual result type is {@code Class<? extends |X|>}* where {@code |X|} is the erasure of the static type of the* expression on which {@code getClass} is called.</b> For* example, no cast is required in this code fragment:</p>** <p>* {@code Number n = 0;                             }<br>* {@code Class<? extends Number> c = n.getClass(); }* </p>** @return The {@code Class} object that represents the runtime*         class of this object.* @jls 15.8.2 Class Literals

廖雪峰

#3 Created at ... [Delete] [Delete and Lock User]

你从面向对象的角度思考是对的,如果严格按继承来搞,虽然理论完美了,但大家都拿不到实际类型了,实际运行就得抓狂,所以JDK的实现是native方法,特事特办。

类似的还有:

为啥interface可以直接向上转型为Object?

这些统统是特例,说明了工程领域的一个深刻道理:

理论再完备,落地也要考虑各种实际情况。


  • 1

Reply