且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中实现反射?

更新时间:2022-10-30 20:29:12

任何反射活动的主要入口都是Class类.从中可以获得MethodFieldClassConstructorAnnotation实例.

The main entry point of any Reflection activity is the Class class. From it you can get Method, Field, Class, Constructor, and Annotation instances.

如果您查看源代码,您会注意到,要检索以上任何内容,Java必须创建一个

If you look at the source code, you will notice that to retrieve any of the above, Java has to make a native call. For example,

private native Field[]       getDeclaredFields0(boolean publicOnly);
private native Method[]      getDeclaredMethods0(boolean publicOnly);
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
private native Class<?>[]   getDeclaredClasses0();
private native byte[] getRawAnnotations(); // get converted to Annotation instances later

该实现是用本机C代码(和/或C ++)完成的.每个JDK可能有所不同,但是您可以在源代码可用并且耐心的情况下查找源代码.有关OpenJDK源代码的详细信息,可以在此问题中 .

The implementation is done in native C code (and/or C++). Each JDK might differ, but you can look up the source code if it's available and you have patience. Details on the OpenJDK source code can be found in this question.