How is Reflection Implemented in Java?

2019-03-30 08:07发布

问题:

The Java 7 Language Specifications say pretty early on:

"this specification does not describe reflection in any detail."

I'm wondering just that: how is Reflection implemented in Java?

I'm not asking how it's used, and I understand there might not be as specific an answer I'm looking for, but any information would be much appreciated.

I've found this on Stackoverflow, the analogous question about C#: How is reflection implemented in C#?

回答1:

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

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

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.