4

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#?

Community
  • 1
  • 1
en_Knight
  • 5,301
  • 2
  • 26
  • 46
  • Pretty much smoke and mirrors. Lots of `native` methods that dork around in the innards of objects. A `native` method pretty much can do anything it wants. – Hot Licks Dec 09 '13 at 02:06

1 Answers1

2

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.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724