C# 6.0 introduced the nameof()
operator, that returns a string representing the name of any class / function / method / local-variable / property identifier put inside it.
If I have a class like this:
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.
Is there any equivalent of that operator in Java? Otherwise, how can I achieve the same result (or similar)?
nameof
is syntactic sugar added in the latest version of C# (6). I'm pretty sure that Java (or most popular languages in general) wouldn't have an equivalent. – Markelnameof()
operator :) – Garlennameof()
does not sound like clean design if it's not for logging etc. – Delagarzanameof(AffectedProperty)
to a relevant property of the event args object to notify listeners as to which property was updated. It's a great way to get compile-time safety for property names. – Markelnameof
feature belongs to that language... – Garlen