Note that there are some explanatory texts on larger screens.

plurals
  1. POJava/Scala obtain a Field reference in a typesafe way
    text
    copied!<p>Java claims to be object oriented and typesafe, and Scala even more so.</p> <p>Internal Class fields are represented by class called Field, which you can obtain a reference to via the Reflection API.</p> <p>My question: do these languages provide any way to obtain that Field reference in a <strong>typesafe</strong> way? (And if not, why on earth not? Seems like a glaring deficiency)</p> <p>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. </p> <p>Ideally I'd like to say something like:</p> <pre><code>&amp;(SomeClass.someField).name() </code></pre> <p>to get the name of the field declaration, similar to how java enums let you say: </p> <pre><code>MyEnum.SOME_INSTANCE.name() </code></pre> <p>[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 <strong>are</strong> known at compile time, namely the Fields of the very class that it's compiling!</p> <p>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.</p> <p>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?</p> <p>[update #2] as for the utility of this feature, have you ever tried using the Criteria API in JPA or Hibernate to dynamically construct a query? Have you seen the absurd work-arounds people have come up with to try to avoid having to pass in an unsafe String representation of the field to query against?</p> <p>[update #3] Finally, a new JVM language called Ceylon has heeded the call and makes this <a href="https://dzone.com/articles/java-scala-ceylon-evolution" rel="nofollow">trivial</a> to do!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload