Jacob
Jacob

Reputation: 4031

Grails get a property by is name

Let's say I have an class like this:

class Termin {
    String someName
}

Then an object

object a = new Termin();

and a variable

String something = a.someName;

How can I get the name of the property someName from the class if I only have the variable something?

Upvotes: 0

Views: 5621

Answers (3)

Will
Will

Reputation: 14529

You can't do that unless you check each property value from the Termin object as per @Igor Artamonov answer. The value you assigned to String something doesn't yield something like a reference to the original object the property belonged.

You can try to work with MetaProperty explicitly, but it will get clumsy:

class Termin {
  String name
}

t = new Termin(name: "john doe")

def something = t.metaClass.properties.find { it.name == "name" }

assert something.getProperty(t) == "john doe"
assert something.field.name == "name"

Upvotes: 1

Thermech
Thermech

Reputation: 4451

I think the easiest way should be:

a."${something}"

Upvotes: 3

Igor Artamonov
Igor Artamonov

Reputation: 35961

Try:

String something = ...
String propertyName = a.properties.entrySet().find { 
   return it.value == something
}?.key

Upvotes: 1

Related Questions