0

I am looking for solution to find the property name of given object in a mother object. I tried iterate through hall the mother object compare with objects with is operator, but I can get the property name from the mother class.

Pseudo Example:

Class Boo {
   List<B> bb_property = []
}
Class Foo {
   List<A> a_property = []
   List<B> b_property = []
   Boo boo = new Boo()
}

Foo foo = new Foo()

List<A> randomname = foo.a_property

String propertyname = foo.findPropertyNameOf(randomname) //this is here where the magic should happen
assert propertyname == "a_property"


List<A> someOtherRandomName = foo.boo.bb_property

propertyname = foo.findPropertyNameOf(someOtherRandomName) //this is here where the magic should happen
assert propertyname == "bb_property"
Dasma
  • 1,023
  • 13
  • 34

1 Answers1

1

Groovy provides a number of ways for you to get the properties on an object. One easy way is the properties method which returns a map of name to value.

That can be seen here: Groovy property iteration

And you can then compare for reference equality (which I assume is what you'd want as opposed to value equality): How can I perform a reference equals in Groovy?

You do have to watch our for cycles through, especially with properties such as class which will definitely have references to itself.

Putting that altogether with just simple avoidance of class/metaClass and not full cycle prevention you can do it as follows:

Object.metaClass.findPropertyNameOf = { v ->
   delegate.properties.collect { pn, pv ->
      pv.is(v) ? pn : (pn in ["class", "metaClass"] ? null : pv.findPropertyNameOf(v))
   }.find { it != null }
}
Steve Sowerby
  • 1,136
  • 1
  • 7
  • 7