[[custom_gradle_types]]
= Developing Custom Gradle Types

There are several different kinds of "add-ons" to Gradle that you can develop, such as <<custom_plugins.adoc#custom_plugins,plugins>>, <<custom_tasks.adoc#custom_tasks,tasks>>,
<<custom_plugins.adoc#sec:getting_input_from_the_build,project extensions>> or <<artifact_transforms.adoc#sec:implementing-artifact-transforms,artifact transforms>>,
that are all implemented as classes and other types that can run on the JVM.
This chapter discusses some of the features and concepts that are common to these types.
You can use these features to help implement custom Gradle types and provide a consistent DSL for your users.

This chapter applies to the following types:

- Plugin types.
- Task types.
- Artifact transform parameters types.
- Worker API work action parameters types.
- Extension objects created using `ExtensionContainer.create()`, for example a project extension registered by a plugin.
- Objects created using `ObjectFactory.newInstance()`.
- Objects created for a managed nested property.
- Elements of a `NamedDomainObjectContainer`.

== Configuration using bean properties

The custom Gradle types that you implement often hold some configuration that you want to make available to build scripts and other plugins.
For example, a download task may have configuration that specifies the URL to download from and the file system location to write the result to.
This configuration is represented as Java bean properties.

Kotlin and Groovy provide conveniences for declaring Java bean properties, which make them good language choices to use to implement Gradle types.
These conveniences are demonstrated in the samples below.

Gradle also provides some conveniences for implementing types with bean properties.

[[managed_properties]]
=== Managed properties

Gradle can provide an implementation of an abstract property. This is called a _managed property_, as Gradle takes care of managing the state of the property.
A property may be _mutable_, meaning that it has both a getter method and setter method, or _read-only_, meaning that it has only a getter method.

[NOTE]
====
Managed properties are currently an <<feature_lifecycle.adoc#feature_lifecycle,incubating>> feature.
====

==== Mutable managed properties

To declare a mutable managed property, add an abstract getter method and an abstract setter method for the property to the type.

Here is an example of a task type with a `uri` property:

.Mutable managed property
====
[source.multi-language-sample,java]
.Download.java
----
include::{snippetsPath}/plugins/mutableManagedProperty/groovy/buildSrc/src/main/java/Download.java[]
----
====

Note that for a property to be considered a mutable managed property, _all_ of the property's getter methods and setter methods must be `abstract` and have `public` or `protected` visibility.

[[read_only_managed_properties]]
==== Read-only managed properties

To declare a read-only managed property, add an abstract getter method for the property to the type.
The property should not have any setter methods.
Gradle will provide an implementation of the getter and also create a value for the property.

This is a useful pattern to use with one of Gradle's configurable <<lazy_configuration.adoc#lazy_configuration,lazy property>> or container types.

Here is an example of a task type with a `uri` property:

.Read-only managed property
====
[source.multi-language-sample,java]
.Download.java
----
include::{snippetsPath}/plugins/readOnlyManagedProperty/groovy/buildSrc/src/main/java/Download.java[]
----
====

Note that for a property to be considered a read only managed property, _all_ of the property's getter methods must be `abstract` and have `public` or `protected` visibility.
The property must not have any setter methods.
In addition, the property type must have one of the following:

- `Property<T>`
- `RegularFileProperty`
- `DirectoryProperty`
- `ListProperty<T>`
- `SetProperty<T>`
- `MapProperty<K, V>`
- `ConfigurableFileCollection`
- `ConfigurableFileTree`
- `DomainObjectSet<T>`
- `NamedDomainObjectContainer<T>`

Gradle creates values for read-only managed properties in the same way as link:{javadocPath}/org/gradle/api/model/ObjectFactory.html[ObjectFactory].

[[read_only_managed_nested_properties]]
==== Read-only managed nested properties

To declare a read-only managed nested property, add an abstract getter method for the property to the type annotated with `@link:{javadocPath}/org/gradle/api/tasks/Nested.html[Nested]`.
The property should not have any setter methods.
Gradle provides an implementation for the getter method, and also creates a value for the property.
The nested type is also treated as a custom type, and can use the features discussed in this chapter.

This pattern is useful when a custom type has a nested complex type which has the same lifecycle.
If the lifecycle is different, consider using `Property<NestedType>` instead.

Here is an example of a task type with a `resource` property. The `Resource` type is also a custom Gradle type and defines some managed properties:

.Read-only managed nested property
====
[source.multi-language-sample,java]
.Download.java
----
include::{snippetsPath}/plugins/readOnlyNestedProperty/groovy/buildSrc/src/main/java/Download.java[tags=download]
include::{snippetsPath}/plugins/readOnlyNestedProperty/groovy/buildSrc/src/main/java/Resource.java[tags=resource]
----
====

Note that for a property to be considered a read only managed nested property, _all_ of the property's getter methods must be `abstract` and have `public` or `protected` visibility.
The property must not have any setter methods.
In addition, the property getter must be annotated with `@link:{javadocPath}/org/gradle/api/tasks/Nested.html[Nested]`.

[[managed_types]]
=== Managed types

A _managed type_ is an abstract class or interface with no fields and whose properties are all managed.
That is, it is a type whose state is entirely managed by Gradle.

== DSL support and extensibility

When Gradle creates an instance of a custom type, it _decorates_ the instance to mix-in DSL and extensibility support.

Each decorated instance implements link:{javadocPath}/org/gradle/api/plugins/ExtensionAware.html[ExtensionAware], and so can have extension
objects attached to it.

Note that plugins and the elements of containers created using link:{javadocPath}/org/gradle/api/Project.html#container-java.lang.Class-[Project.container()] are currently not decorated, due to backwards compatibility issues.

[[service_injection]]
== Service injection

Gradle provides a number of useful services that can be used by custom Gradle types.
For example, the link:{javadocPath}/org/gradle/workers/WorkerExecutor.html[WorkerExecutor] service can be used by a task to run work in parallel, as seen in the <<custom_tasks.adoc#worker_api,worker API>> section.
The services are made available through _service injection_.

[[services_for_injection]]
=== Available services

The following services are available for injection:

- link:{javadocPath}/org/gradle/api/model/ObjectFactory.html[ObjectFactory] - Allows model objects to be created. See <<#nested_objects>> for more details.
- link:{javadocPath}/org/gradle/api/file/ProjectLayout.html[ProjectLayout] - Provides access to key project locations. See <<lazy_configuration.adoc#working_with_files_in_lazy_properties,lazy configuration>> for more details. This service is unavailable in Worker API actions.
- link:{javadocPath}/org/gradle/api/provider/ProviderFactory.html[ProviderFactory] - Creates `Provider` instances. See <<lazy_configuration.adoc#lazy_configuration,lazy configuration>> for more details.
- link:{javadocPath}/org/gradle/workers/WorkerExecutor.html[WorkerExecutor] - Allows a task to run work in parallel. See <<custom_tasks.adoc#worker_api,the worker API>> for more details.
- link:{javadocPath}/org/gradle/api/file/FileSystemOperations.html[FileSystemOperations] - Allows a task to run operations on the filesystem such as deleting files, copying files or syncing directories.
- link:{javadocPath}/org/gradle/api/file/ArchiveOperations.html[ArchiveOperations] - Allows a task to run operations on archive files such as ZIP or TAR files.
- link:{javadocPath}/org/gradle/process/ExecOperations.html[ExecOperations] - Allows a task to run external processes with dedicated support for running external `java` programs.
- link:{javadocPath}/org/gradle/tooling/provider/model/ToolingModelBuilderRegistry.html[ToolingModelBuilderRegistry] - Allows a plugin to registers a Gradle tooling API model.

Out of the above, `ProjectLayout` and `WorkerExecutor` services are only available for injection in project plugins.

=== Constructor injection

There are 2 ways that an object can receive the services that it needs. The first option is to add the service as a parameter of the class constructor.
The constructor must be annotated with the `javax.inject.Inject` annotation.
Gradle uses the declared type of each constructor parameter to determine the services that the object requires.
The order of the constructor parameters and their names are not significant and can be whatever you like.

Here is an example that shows a task type that receives an `ObjectFactory` via its constructor:

.Constructor service injection
====
[source.multi-language-sample,java]
.Download.java
----
include::{snippetsPath}/plugins/constructorServiceInjection/groovy/buildSrc/src/main/java/Download.java[]
----
====

=== Property injection

Alternatively, a service can be injected by adding a property getter method annotated with the `javax.inject.Inject` annotation to the class.
This can be useful, for example, when you cannot change the constructor of the class due to backwards compatibility constraints.
This pattern also allows Gradle to defer creation of the service until the getter method is called, rather than when the instance is created. This can help with performance.
Gradle uses the declared return type of the getter method to determine the service to make available. The name of the property is not significant and can be whatever you like.

The property getter method must be `public` or `protected`. The method can be `abstract` or, in cases where this isn't possible, can have a dummy method body.
The method body is discarded.

Here is an example that shows a task type that receives a two services via property getter methods:

.Property service injection
====
[source.multi-language-sample,java]
.Download.java
----
include::{snippetsPath}/plugins/propertyServiceInjection/groovy/buildSrc/src/main/java/Download.java[]
----
====

[[nested_objects]]
== Creating nested objects

A custom Gradle type can use the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html[ObjectFactory] service to create instances of Gradle types to use for its property values.
These instances can make use of the features discussed in this chapter, allowing you to create 'nested' object and a nested DSL.

You can also have Gradle create nested objects for you by using a <<read_only_managed_nested_properties,managed nested property>>.

In the following example, a project extension receives an `ObjectFactory` instance through its constructor.
The constructor uses this to create a nested `Resource` object (also a custom Gradle type) and makes this object available through the `resource` property.

.Nested object creation
====
[source.multi-language-sample,java]
.DownloadExtension.java
----
include::{snippetsPath}/plugins/nestedObjects/groovy/buildSrc/src/main/java/DownloadExtension.java[]
include::{snippetsPath}/plugins/nestedObjects/groovy/buildSrc/src/main/java/Resource.java[tags=resource]
----
====

[[collection_types]]
== Collection types

Gradle provides types for maintaining collections of objects, intended to work well with the Gradle DSL and provide useful features such as lazy configuration.

=== NamedDomainObjectContainer

A link:{javadocPath}/org/gradle/api/NamedDomainObjectContainer.html[NamedDomainObjectContainer] manages a set of objects, where each element has a name associated with it.
The container takes care of creating and configuring the elements, and provides a DSL that build scripts can use to define and configure elements.
It is intended to hold objects which are themselves configurable, for example a set of custom Gradle objects.

Gradle uses `NamedDomainObjectContainer` type extensively throughout the API.
For example, the `project.tasks` object used to manage the tasks of a project is a `NamedDomainObjectContainer<Task>`.

You can create a container instance using the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html[ObjectFactory] service, which provides the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#domainObjectContainer-java.lang.Class-[ObjectFactory.domainObjectContainer()] method.
This is also available using the link:{javadocPath}/org/gradle/api/Project.html#container-java.lang.Class-[Project.container()] method, however in a custom Gradle type it's
generally better to use the injected `ObjectFactory` service instead of passing around a `Project` instance.

You can also create a container instance using a <<read_only_managed_properties,read-only managed property>>, described above.

In order to use a type with any of the `domainObjectContainer()` methods, it must expose a property named "`name`" as the unique, and constant, name for the object.
The `domainObjectContainer(Class)` variant of the method creates new instances by calling the constructor of the class that takes a string argument, which is the desired name of the object.
Objects created this way are treated as custom Gradle types, and so can make use of the features discussed in this chapter, for example service injection or managed properties.

See the above link for `domainObjectContainer()` method variants that allow custom instantiation strategies.

.Managing a collection of objects
====
[source.multi-language-sample,java]
.DownloadExtension.java
----
include::{snippetsPath}/plugins/namedDomainObjectContainer/groovy/buildSrc/src/main/java/DownloadExtension.java[]
include::{snippetsPath}/plugins/namedDomainObjectContainer/groovy/buildSrc/src/main/java/Resource.java[tags=resource]
----
====

For each container property, Gradle automatically adds a block to the Groovy and Kotlin DSL that you can use to configure the
contents of the container:

.Configure block
====
[source.multi-language-sample,kotlin]
.build.gradle.kts
----
include::{snippetsPath}/plugins/namedDomainObjectContainer/kotlin/build.gradle.kts[]
----
[source.multi-language-sample,groovy]
.build.gradle
----
include::{snippetsPath}/plugins/namedDomainObjectContainer/groovy/build.gradle[]
----
====

=== ExtensiblePolymorphicDomainObjectContainer

An link:{javadocPath}/org/gradle/api/ExtensiblePolymorphicDomainObjectContainer.html[ExtensiblePolymorphicDomainObjectContainer] is a `NamedDomainObjectContainer` that allows you to
define instantiation strategies for different types of objects.

You can create an instance using the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#polymorphicDomainObjectContainer-java.lang.Class-[ObjectFactory.polymorphicDomainObjectContainer()] method.

=== NamedDomainObjectSet

A link:{javadocPath}/org/gradle/api/NamedDomainObjectSet.html[NamedDomainObjectSet] holds a set of configurable objects, where each element has a name associated with it.
This is similar to `NamedDomainObjectContainer`, however a `NamedDomainObjectSet` doesn't manage the objects in the collection. They need to be created and added manually.

You can create an instance using the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#namedDomainObjectSet-java.lang.Class-[ObjectFactory.namedDomainObjectSet()] method.

=== NamedDomainObjectList

A link:{javadocPath}/org/gradle/api/NamedDomainObjectList.html[NamedDomainObjectList] holds a list of configurable objects, where each element has a name associated with it.
This is similar to `NamedDomainObjectContainer`, however a `NamedDomainObjectList` doesn't manage the objects in the collection. They need to be created and added manually.

You can create an instance using the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#namedDomainObjectList-java.lang.Class-[ObjectFactory.namedDomainObjectList()] method.

=== DomainObjectSet

A link:{javadocPath}/org/gradle/api/DomainObjectSet.html[DomainObjectSet] simply holds a set of configurable objects.
Compared to `NamedDomainObjectContainer`, a `DomainObjectSet` doesn't manage the objects in the collection. They need to be created and added manually.

You can create an instance using the link:{javadocPath}/org/gradle/api/model/ObjectFactory.html#domainObjectSet-java.lang.Class-[ObjectFactory.domainObjectSet()] method.
