代码之家  ›  专栏  ›  技术社区  ›  Dasma

是否可以找到对象属性名

  •  0
  • Dasma  · 技术社区  · 6 年前

    我正在寻找解决方案,以找到在母对象中给定对象的属性名。我尝试在hall中迭代母对象compare with objects with is操作符,但我可以从母类中获取属性名。

    伪示例:

    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"
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Steve Sowerby    6 年前

    Groovy为您提供了许多获取对象属性的方法。一个简单的方法是 properties 方法返回名称到值的映射。

    在这里可以看到: Groovy property iteration

    然后,您可以比较引用相等性(我假设这是您想要的,而不是值相等性): How can I perform a reference equals in Groovy?

    你一定要注意我们的循环,特别是像 class 肯定会提到它自己。

    加上简单的避免类/元类和 全周期预防您可以按以下步骤进行:

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