Groovyで次のようなことをする方法はありますか:
class Person{
def name, surname
}
public void aMethod(anoherBean){
def bean = retrieveMyBean()
p.properties = anoherBean.properties
}
プロパティのプロパティは最終的なものです。このショートカットを実行する別の方法はありますか?
Groovyで次のようなことをする方法はありますか:
class Person{
def name, surname
}
public void aMethod(anoherBean){
def bean = retrieveMyBean()
p.properties = anoherBean.properties
}
プロパティのプロパティは最終的なものです。このショートカットを実行する別の方法はありますか?
特別な理由がない場合は、名前付きパラメーターを使用してください
def p = new Person(name: 'John', surname: 'Lennon')
質問が更新された後
static copyProperties(from, to) {
from.properties.each { key, value ->
if (to.hasProperty(key) && !(key in ['class', 'metaClass']))
to[key] = value
}
}
properties
仮想プロパティです。個々のセッターを呼び出す必要があります。これを試して:
def values = [name: 'John', surname: 'Lennon']
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
または、MOP を使用して:
Object.class.putAllProperties = { values ->
for( def entry : values.entries() ) {
p.setProperty( entry.getKey(), entry.getValue() );
}
}
Person p = new Person();
p.putAllProperties [name: 'John', surname: 'Lennon']
[編集]目的を達成するには、プロパティをループする必要があります。このブログ投稿では、その方法について説明しています。
def copyProperties(def source, def target){
target.metaClass.properties.each{
if (source.metaClass.hasProperty(source, it.name) && it.name != 'metaClass' && it.name != 'class')
it.setProperty(target, source.metaClass.getProperty(source, it.name))
}
}