getClass()是如何在java中实现的? [英] How does the getClass() is implemented in java?

查看:80
本文介绍了getClass()是如何在java中实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

public class QueueSample {

    public static void main(String[] args) {
        System.out.println(new QueueSample().getClass());
    }

}

打印:

class QueueSample

getClass()方法来自 Object 类。查看 Object 的源代码,我只能看到这样的方法定义:

getClass() method is coming from the Object class. Looking at the source code of Object, I can see only method definition like this:

public final native Class<?> getClass();

如果未在此处实施,此方法在何处以及如何实施?

If its not implemented here, where and how does this method got implemented?

推荐答案

正如@TheLostMind所提到的,你可以从OpenJDK获取源代码 - 看一下较新版本(JDK9) getClass()本机方法实现如

As @TheLostMind mentions, you can get the source code from OpenJDK - looking into a somewhat newer version (JDK9), the getClass() native method is implemented like

JNIEXPORT jclass JNICALL
Java_java_lang_Object_getClass(JNIEnv *env, jobject this)
{
    if (this == NULL) {
        JNU_ThrowNullPointerException(env, NULL);
        return 0;
    } else {
        return (*env)->GetObjectClass(env, this);
    }
}

所以,它的作用基本上是委托给JVM的环境并使用 GetObjectClass()函数返回 Class 对象。您可以将此作为起点 - 如果您想深入了解,我建议您查看来自 http://hg.openjdk.java.net/ 使用mercurial,以便您可以浏览它。

So, essentially what it does is it delegates to the JVM's environment and uses the GetObjectClass() function to return the Class object. You can use this as a starting point - if you want to go deeper, I suggest that you check out the JDK source code from http://hg.openjdk.java.net/ using mercurial, so that you can browse through it.

正如@Holger所提到的,有使用JTP编译器(如热点)时的一些性能优化 - 例如,使用的性能技术Hotspot JVM Object.getClass()是一两条指令。这意味着上面的代码显示了 Object.getClass()的一种可能的实现,但是这个实现可能在运行时和/或基于实际的JVM(解释/ JITted,客户端/服务器,Oracle标准/ JRockit,...)

As @Holger mentions, there are some performance optimizations when using a JIT compiler such as hotspot - for example, Performance techniques used in the Hotspot JVM says "Object.getClass() is one or two instructions.". What this means is that the above code shows one possible implementation of Object.getClass(), but this implementation might change during runtime and/or based on the actual JVM (interpreted/JITted, client/server, Oracle standard/JRockit, ...)

这篇关于getClass()是如何在java中实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆