2

文字列からGroovyクラスにプロパティを動的に追加することは可能ですか?
たとえば、ユーザーに「HelloString」などの文字列を挿入するように依頼し、
プロパティ HelloString を既存の Groovy グラスに追加しますか?

4

2 に答える 2

5

これに対処するにはいくつかの方法があります。たとえば、使用できますpropertyMissing

class Foo {
   def storage = [:]
   def propertyMissing(String name, value) { storage[name] = value }
   def propertyMissing(String name) { storage[name] }
}
def f = new Foo()
f.foo = "bar"

assertEquals "bar", f.foo

既存のクラス(任意のクラス)の場合、使用できますExpandoMetaClass

class Book {
  String title
}
Book.metaClass.getAuthor << {-> "Stephen King" }

def b = new Book("The Stand")

assert "Stephen King" == b.author

Expandoまたはクラスを使用するだけで:

def d = new Expando()
d."This is some very odd variable, but it works!" = 23
println d."This is some very odd variable, but it works!"

または@Delegateストレージとしてマップに:

class C {
    @Delegate Map<String,Object> expandoStyle = [:]
}
def c = new C()
c."This also" = 42
println c."This also"

そして、これは var によってプロパティを設定する方法です:

def userInput = 'This is what the user said'
c."$userInput" = 666
println c."$userInput"
于 2014-09-23T10:38:20.393 に答える