C# 6.0 引入了 nameof()
操作符,它返回一个字符串,表示放入其中的任何类/函数/方法/局部变量/属性标识符的名称。
如果我有这样的类(class):
class MyClass
{
public SomeOtherClass MyProperty { get; set; }
public void MyMethod()
{
var aLocalVariable = 12;
}
}
我可以像这样使用运算符:
// with class name:
var s = nameof(MyClass); // s == "MyClass"
// with properties:
var s = nameof(MyClass.OneProperty); // s == "OneProperty"
// with methods:
var s = nameof(MyClass.MyMethod); // s == "MyMethod"
// with local variables:
var s = nameof(aLocalVariable); // s == "aLocalVariable".
这很有用,因为在编译时会检查正确的字符串。如果我拼错了某些属性/方法/变量的名称,编译器会返回错误。此外,如果我重构,所有字符串都会自动更新。参见示例 this documentation用于实际用例。
在 Java 中有与该运算符等效的吗?否则,我怎样才能达到相同(或相似)的结果?
最佳答案
可以使用运行时字节码检测来完成,例如使用 Byte Buddy 库。
查看此库:https://github.com/strangeway-org/nameof
这里描述了该方法:http://in.relation.to/2016/04/14/emulating-property-literals-with-java-8-method-references/
使用示例:
public class NameOfTest {
@Test
public void direct() {
assertEquals("name", $$(Person.class, Person::getName));
}
@Test
public void properties() {
assertEquals("summary", Person.$(Person::getSummary));
}
}
关于java - Java 中的等价名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40850926/