想请问一下,什么是原生方法(native methods)?可以举个列子吗?

在网上自己搜了一下,原生方法是依赖于平台的方法,同时不是以java语言实现,而是以更低级的语言,如C或C++,同时说在Class 类中定义的大部分方法均为原生方法,可以举个Class 类中的例子吗?

jdk源码中有很多native方法,随手复制几个出来吧:

public static native Thread currentThread; /** * A hint to the scheduler that the current thread is willing to yield * its current use of a processor. The scheduler is free to ignore this * hint. * * <p> Yield is a heuristic attempt to improve relative progression * between threads that would otherwise over-utilise a CPU. Its use * should be combined with detailed profiling and benchmarking to * ensure that it actually has the desired effect. * * <p> It is rarely appropriate to use this method. It may be useful * for debugging or testing purposes, where it may help to reproduce * bugs due to race conditions. It may also be useful when designing * concurrency control constructs such as the ones in the * {@link java.util.concurrent.locks} package. */ public static native void yield; /** * Causes the currently executing thread to sleep temporarily cease * execution for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The thread * does not lose ownership of any monitors. * * @param millis * the length of time to sleep in milliseconds * * @throws IllegalArgumentException * if the value of {@code millis} is negative * * @throws InterruptedException * if any thread has interrupted the current thread. The * <i>interrupted status</i> of the current thread is * cleared when this exception is thrown. */ public static native void sleeplong millis throws InterruptedException;

1.6的Class.c。反正我是看不懂。。。

/* * Copyright c 1994, 2004, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details a copy is included in the LICENSE file that * accompanied this code. * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /*- * Implementation of class Class * * former threadruntime.c, Sun Sep 22 12:09:39 1991 */ #include <string.h>
#include <stdlib.h> #include "jni.h"
#include "jni_util.h"
#include "jvm.h"
#include "java_lang_Class.h" /* defined in libverify.so/verify.dll src file common/check_format.c */
extern jboolean VerifyClassnamechar *utf_name, jboolean arrayAllowed;
extern jboolean VerifyFixClassnamechar *utf_name; #define OBJ "Ljava/lang/Object;"
#define CLS "Ljava/lang/Class;"
#define CPL "Lsun/reflect/ConstantPool;"
#define STR "Ljava/lang/String;"
#define JCL "Ljava/lang/ClassLoader;"
#define FLD "Ljava/lang/reflect/Field;"
#define MHD "Ljava/lang/reflect/Method;"
#define CTR "Ljava/lang/reflect/Constructor;"
#define PD "Ljava/security/ProtectionDomain;"
#define BA "[B" static JNINativeMethod methods[] = { {"getName0", "" STR, void *&JVM_GetClassName}, {"getSuperclass", "" CLS, NULL}, {"getInterfaces", "[" CLS, void *&JVM_GetClassInterfaces}, {"getClassLoader0", "" JCL, void *&JVM_GetClassLoader}, {"isInterface", "Z", void *&JVM_IsInterface}, {"getSigners", "[" OBJ, void *&JVM_GetClassSigners}, {"setSigners", "[" OBJ "V", void *&JVM_SetClassSigners}, {"isArray", "Z", void *&JVM_IsArrayClass}, {"isPrimitive", "Z", void *&JVM_IsPrimitiveClass}, {"getComponentType", "" CLS, void *&JVM_GetComponentType}, {"getModifiers", "I", void *&JVM_GetClassModifiers}, {"getDeclaredFields0","Z[" FLD, void *&JVM_GetClassDeclaredFields}, {"getDeclaredMethods0","Z[" MHD, void *&JVM_GetClassDeclaredMethods}, {"getDeclaredConstructors0","Z[" CTR, void *&JVM_GetClassDeclaredConstructors}, {"getProtectionDomain0", "" PD, void *&JVM_GetProtectionDomain}, {"setProtectionDomain0", "" PD "V", void *&JVM_SetProtectionDomain}, {"getDeclaredClasses0", "[" CLS, void *&JVM_GetDeclaredClasses}, {"getDeclaringClass", "" CLS, void *&JVM_GetDeclaringClass}, {"getGenericSignature", "" STR, void *&JVM_GetClassSignature}, {"getRawAnnotations", "" BA, void *&JVM_GetClassAnnotations}, {"getConstantPool", "" CPL, void *&JVM_GetClassConstantPool}, {"desiredAssertionStatus0",""CLS"Z",void *&JVM_DesiredAssertionStatus}, {"getEnclosingMethod0", "[" OBJ, void *&JVM_GetEnclosingMethodInfo}
}; #undef OBJ
#undef CLS
#undef STR
#undef JCL
#undef FLD
#undef MHD
#undef CTR
#undef PD JNIEXPORT void JNICALL
Java_java_lang_Class_registerNativesJNIEnv *env, jclass cls
{ methods[1].fnPtr = void **env->GetSuperclass; *env->RegisterNativesenv, cls, methods, sizeofmethods/sizeofJNINativeMethod;
} JNIEXPORT jclass JNICALL
Java_java_lang_Class_forName0JNIEnv *env, jclass this, jstring classname, jboolean initialize, jobject loader
{ char *clname; jclass cls = 0; char buf[128]; int len; int unicode_len; if classname == NULL { JNU_ThrowNullPointerExceptionenv, 0; return 0; } len = *env->GetStringUTFLengthenv, classname; unicode_len = *env->GetStringLengthenv, classname; if len >= sizeofbuf { clname = malloclen + 1; if clname == NULL { JNU_ThrowOutOfMemoryErrorenv, NULL; return NULL; } } else { clname = buf; } *env->GetStringUTFRegionenv, classname, 0, unicode_len, clname; if VerifyFixClassnameclname == JNI_TRUE { /* slashes present in clname, use name b4 translation for exception */ *env->GetStringUTFRegionenv, classname, 0, unicode_len, clname; JNU_ThrowClassNotFoundExceptionenv, clname; goto done; } if !VerifyClassnameclname, JNI_TRUE { /* expects slashed name */ JNU_ThrowClassNotFoundExceptionenv, clname; goto done; } cls = JVM_FindClassFromClassLoaderenv, clname, initialize, loader, JNI_FALSE; done: if clname != buf { freeclname; } return cls;
} JNIEXPORT jboolean JNICALL
Java_java_lang_Class_isInstanceJNIEnv *env, jobject cls, jobject obj
{ if obj == NULL { return JNI_FALSE; } return *env->IsInstanceOfenv, obj, jclasscls;
} JNIEXPORT jboolean JNICALL
Java_java_lang_Class_isAssignableFromJNIEnv *env, jobject cls, jobject cls2
{ if cls2 == NULL { JNU_ThrowNullPointerExceptionenv, 0; return JNI_FALSE; } return *env->IsAssignableFromenv, cls2, cls;
} JNIEXPORT jclass JNICALL
Java_java_lang_Class_getPrimitiveClassJNIEnv *env, jclass cls, jstring name
{ const char *utfName; jclass result; if name == NULL { JNU_ThrowNullPointerExceptionenv, 0; return NULL; } utfName = *env->GetStringUTFCharsenv, name, 0; if utfName == 0 return NULL; result = JVM_FindPrimitiveClassenv, utfName; *env->ReleaseStringUTFCharsenv, name, utfName; return result;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注