API 文件 | ExtensionAware |
---|
可以在運行時使用其他物件擴充的物件。
// Extensions are just plain objects, there is no interface/type class MyExtension { String foo MyExtension(String foo) { this.foo = foo } } // Add new extensions via the extension container project.extensions.create('custom', MyExtension, "bar") // («name», «type», «constructor args», …) // extensions appear as properties on the target object by the given name assert project.custom instanceof MyExtension assert project.custom.foo == "bar" // also via a namespace method project.custom { assert foo == "bar" foo = "other" } assert project.custom.foo == "other" // Extensions added with the extension container's create method are themselves extensible assert project.custom instanceof ExtensionAware project.custom.extensions.create("nested", MyExtension, "baz") assert project.custom.nested.foo == "baz" // All extension aware objects have a special "ext" extension of type ExtraPropertiesExtension assert project.hasProperty("myProperty") == false project.ext.myProperty = "myValue" // Properties added to the "ext" extension are promoted to the owning object assert project.myProperty == "myValue"
許多 Gradle 物件都具有擴充感知能力。這包括:專案、任務、組態、相依性等。
有關新增和建立擴充功能的更多資訊,請參閱 ExtensionContainer
。
有關額外屬性的更多資訊,請參閱 ExtraPropertiesExtension
。
一個 ExtensionAware
物件有多個 Gradle 搜尋屬性的「範圍」。這些範圍是
- 物件本身。此範圍包括實作類別宣告的任何屬性 getter 和 setter。此範圍的屬性是可讀或可寫的,具體取決於是否存在相應的 getter 或 setter 方法。
- 物件類別實作的 Groovy 元編程方法,例如
propertyMissing()
。外掛作者必須謹慎確保propertyMissing()
的實作方式為:如果找不到屬性,則會擲回 MissingPropertyException(String, Class) 例外。如果propertyMissing()
始終為任何屬性傳回值,Gradle 將不會搜尋以下其餘範圍。 - 物件的額外屬性。每個物件都維護一個額外屬性映射,其中可以包含任何任意名稱 -> 值對。定義後,此範圍的屬性是可讀寫的。
- 外掛程式新增至物件的擴充功能。每個擴充功能都作為唯讀屬性提供,其名稱與擴充功能相同。
屬性 | 描述 |
extensions | 擴充功能的容器。 |
ExtensionContainer
extensions
(唯讀)
擴充功能的容器。