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

607 Views Asked by At

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.

3

There are 3 best solutions below

1
On

I would say that the main reason for the absence of such a feature is that it would not be useful.

Why would we ever ask for meta-information of a specific field in a specific class?

If we hardcode the class and field pair, then we already know all of the field's meta-information, because they can't be changed at runtime. What would be the purpose of the information obtained via Foo.class.bar.getType() when we already know that the result is Integer.class?

1
On

Theoretically I wouldn't call class property/field a 'meta' field. Meta-data is assigned to properties/fields through java annotations and this meta-data is accessed through reflection. By doing Foo.class.bar you destroy the whole point of the object-orientation of this beatiful static language. (Or in other words java is not groovy enough to do it))

0
On

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.