Alex Rivera | Logout

Java/Scala obtain a Field reference in a typesafe way

Asked 2012-03-24T21:23:16.057
11

Java claims to be object oriented and typesafe, and Scala even more so.

Internal Class fields are represented by class called Field, which you can obtain a reference to via the Reflection API.

My question: do these languages provide any way to obtain that Field reference in a typesafe way? (And if not, why on earth not? Seems like a glaring deficiency)

It would be extremely useful when mapping an Object to some external representation, for example to html fields in a template, or to column names in a database, to keep the reference names automatically in sync.

Ideally I'd like to say something like:

&(SomeClass.someField).name() 

to get the name of the field declaration, similar to how java enums let you say:

MyEnum.SOME_INSTANCE.name()

[update:] after reading feedback that this functionality would somehow violate the intent of the Reflection API, I agree that Reflection is designed for things that aren't known at compile time, and that's exactly why it's so absurd to have to use it to learn things that are known at compile time, namely the Fields of the very class that it's compiling!

The compiler provides this for enums, so if the compiler is able to access the enum Field's reference to allow MyEnum.SOME_INSTANCE.name(), then there's no logical reason why it shouldn't also be able to provide this same functionality to ordinary Classes.

Is there any technological reason why this functionality couldn't be there for ordinary classes? I don't see why not, and I disagree that this functionality would "complicate" things... on the contrary it would vastly simplify the present cumbersome Reflection API techniques. Why force developers into Reflection to find out something that is known at compile time?

[update #2] as for the utility of this feature, have you ever tried using the Criteria API in JPA or

Edit
Report

1 Answer

1

Why on earth not is because you don't know the type of the field at compile-time when using reflection. This is the whole point of reflection: to give you access to class information at runtime. Of course you'll get a runtime error if you use the wrong type, but that doesn't really help much.

Unfortunately, as tricky as it is to keep names the same, it's typically even trickier to keep types the same, so it's probably not worth it for the application you have in mind.

Right now there's no way to do what you want with reasonable effort in either Scala or Java. Scala could add this information to its manifests (or somewhere else), but it doesn't presently and it's not clear to me that it's worth the effort.

answered 2012-03-24T21:52:05.463

Your Answer