nameof equivalent in Java

前端 未结 4 538
生来不讨喜
生来不讨喜 2020-12-16 09:35

C# 6.0 introduced the nameof() operator, that returns a string representing the name of any class / function / method / local-variable / property identifier put

4条回答
  •  余生分开走
    2020-12-16 10:35

    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));
        }
    }
    

提交回复
热议问题