Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't it possible to refer to meta fields or methods in Java?

e.g. with

class Foo {
  Integer bar;
}

I wonder why there isn't a language feature that enables me to do

Foo.class.bar //yes, xxx.class returns something of java.lang.Class<T>

to refer to the meta field bar?

I'm reading the Pro JPA 2 Book and it seems to me the canonical metamodel generation is necessary, because this isn't possible in Java.

Note, this is a theoretical question out of curiosity, where I would like to gain some insights, why this feature wasn't implemented.

--- Update ---

To elaborate my question a bit more, consider the example of adding attributes in JPA by the Entity Graph API:

EntityGraph<Foo> g = myEntityManager.createEntityGraph(Foo.class)
g.addAttributeNodes("bar")

There is no formal link (for the compiler / the IDEs) between the string "bar" and Foo´s attribute bar.

like image 819
Stefan K. Avatar asked Nov 10 '22 10:11

Stefan K.


1 Answers

Because .class is not a magic field that returns your current class at compile time, it's just a sugar to replace getClass() method, that will be executed only in runtime on the instance of Class object. Implementing your 'feature' needs the reconstruction of a whole concept.

The most believable theory that answers your question will be based on the idea, that your 'feature' did not look really 'useful' at the time, when reflection model was designed in Java.

like image 91
AdamSkywalker Avatar answered Nov 14 '22 23:11

AdamSkywalker