In .NET we could write code like the following to return the propertyName
public static string GetName(Expression<Func<object>> exp)
{
MemberExpression body = exp.Body as MemberExpression;
if (body == null) {
UnaryExpression ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
public class Test
{
public string prop1 { get; set; }
}
Inside of properties, we usually use OnPropertyChanged(() => this.prop1) which would return the propertyName. For more info, see this post(How to raise PropertyChanged event without using string name)
I want to do something simular in groovy, but I am not sure the right way to do this.
class TestObj
{
def prop1 = "value"
def prop2 = "value"
}
class Test{
def something(){
def t1 = new TestObj()
def propertyName1 = getName{ t1.prop1 }
def propertyName2 = getName{ t1.prop2 }
assert propertyName1 == "prop1"
assert propertyName2 == "prop2"
}
}
How would you implment the getName method in groovy using an expression as seen above