Java中的等价名称 [英] nameof equivalent in Java

查看:121
本文介绍了Java中的等价名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#6.0引入了 nameof()运算符,该运算符返回一个字符串,表示放在其中的任何类/函数/方法/局部变量/属性标识符的名称。

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

如果我有这样的课程:

class MyClass
{
    public SomeOtherClass MyProperty { get; set; }

    public void MyMethod()
    {
        var aLocalVariable = 12;
    }
}

我可以像这样使用运算符:

I can use the operator like this:

//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 is useful since the correct string is checked at compile time. If I misspell the name of some property/method/variable the compiler returns an error. Also, if I refactor, all the strings are automatically updated. See for example this documentation for real use cases.

Java中是否有该运算符的等价物?否则,我怎样才能获得相同的结果(或相似)?

Is there any equivalent of that operator in Java? Otherwise, how can I achieve the same result (or similar)?

推荐答案

可悲的是,没有这样的结果。我一直在寻找这个功能,答案似乎是一般来说,这个东西不存在。

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.

参见获取字段名称

当然,您可以使用命名注释来注释您的字段,从根本上为您自己的类完成此目标。实际上,有各种各样的框架依赖于类似的概念。即便如此,这也不是自动的。

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.

这篇关于Java中的等价名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆