私はhasProperty()
とプロパティを最初に確認することを避けるための方法を探しています。Gradle findPropertyに相当するGroovyはありますか?
理想的には私は私はGradleのはfindProperty()
を持っていますが、私は、プレーングルーヴィーための同じようなことを見つけることができないことがわかり
のようなものを持っていると思います。私は考えることができ
私はhasProperty()
とプロパティを最初に確認することを避けるための方法を探しています。Gradle findPropertyに相当するGroovyはありますか?
理想的には私は私はGradleのはfindProperty()
を持っていますが、私は、プレーングルーヴィーための同じようなことを見つけることができないことがわかり
のようなものを持っていると思います。私は考えることができ
最短バージョンは明らかに二回、プロパティ名を繰り返し
def a = if (a.hasProperty("mypropname")) a.getProperty("mypropname") else "defaultvalueifmissing"
です。独自のメソッドを作成することは可能ですが、現在のクラスに限定されています。
class MyClass {
String name = "the name"
}
def a = new MyClass()
def getProperty(Object theInstance, String propName, Object defaultValue) {
if (theInstance.hasProperty(propName)) theInstance.getProperty(propName) else defaultValue
}
assert "the name" == getProperty(a, "name", "")
assert "default value" == getProperty(a, "method", "default value")
hasProperty
方法は、あなたが元のインスタンスを渡すことで値を取得するために使用することができますMetaProperty
インスタンスを返します。
def a = myobj.hasProperty('mypropname')?.getProperty(myobj) ?:
'defaultvalueifpropertymissing'
をそして安全なナビゲーション演算子(?.
)とエルビス演算子を使用します(?:
)を使用してif/else
を回避します。
myobjの繰り返しはまだ気になりますが、プロパティ名を繰り返すよりも優れています – ecerulm
一つMetaClassのgetProperties()
またはGroovyObjectのgetProperty()
を使用することができます。
class Test {
String field1
String field2
}
def test = new Test(field1: "value1", field2: null)
// using MetaClass.getProperties()
println test.properties["field1"] // value1
println test.properties["field2"] // null
println "field2" in test.properties.keySet() // true
println test.properties["field3"] // null
println "field3" in test.properties.keySet() // false
// using GroovyObject.getProperty()
println test.getProperty("field1") // value1
println test.getProperty("field2") // null
println test.getProperty("field3") // groovy.lang.MissingPropertyException
の
可能な複製[?オブジェクトが特定のプロパティを持つかどうかを確認する方法](https://stackoverflow.com/questions/12937579/how -to-verify-object-has-certain-propertyの場合) –
私は、この質問に 'getPropertyOrElse'の実装を追加しました(これは重複のため適切な場所です) - https:// stackoverflow。 com/questions/12937579 –
この質問は、プロパティが存在するかどうかを確認するソリューションを明示的に求めています。これは、私が避けようとしているものです。私は、明示的なチェックを避ける便利なメソッド/構文があるかどうかを尋ねています。 – ecerulm