Reputation: 139
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?
Upvotes: 1
Views: 288
Reputation: 2295
In general, the Java language specification says that an expression of this form must return the corresponding class object, but it does not define how this has to be done. The Eclipse JDT compiler actually does not make it a field. It creates a method called "$class" that is called whenever you access something like myClass.class.
Upvotes: 0
Reputation: 13041
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.
Upvotes: 1