Reading on class loading, http://onjava.com/pub/a/onjava/2005/01/26/classloading.html, came across –
“……Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code. Since this field is public, we can access it using dotted notation, like this:
java.lang.Class klass = Myclass.class;
…………”
i tried accessing this field (Myclass.class) using reflection, which is plain insane i agree but still 🙂 and i get java.lang.NoSuchFieldException: class
Myclass myObject = new Myclass;
System.out.println(myObject.getclass().getField("class"));
Is it then the runtime and not the compiler that adds the static .class field? Even then why is it not accessible using reflection?
This is not a field access, per se, but rather an expression of the Java language syntax that merely looks like a field access. I suppose it’s possible for a compiler to put such a synthetic field into the classfile, though I don’t know of one that does.