nameof equivalent in Java

It can be done using runtime byte code instrumentation, for instance using Byte Buddy library.

See this library: https://github.com/strangeway-org/nameof

The approach is described here: http://in.relation.to/2016/04/14/emulating-property-literals-with-java-8-method-references/

Usage example:

public class NameOfTest {
    @Test
    public void direct() {
        assertEquals("name", $$(Person.class, Person::getName));
    }

    @Test
    public void properties() {
        assertEquals("summary", Person.$(Person::getSummary));
    }
}

Sadly, there is nothing like this. I had been looking for this functionality a while back and the answer seemed to be that generally speaking, this stuff does not exist.

See Get name of a field

You could, of course, annotate your field with a "Named" annotation to essentially accomplish this goal for your own classes. There's a large variety of frameworks that depend upon similar concepts, actually. Even so, this isn't automatic.

Tags:

Java

Nameof