W3cubDocs

/Groovy 3.0

[Java] Annotation Type ClosureParams

  • groovy.transform.stc.ClosureParams
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ClosureParams

Parameter annotation aimed at helping IDEs or the static type checker to infer the parameter types of a closure. Without this annotation, a method signature may look like this:

public <T,R> List<R> doSomething(List<T> source, Closure<R> consumer)

The problem this annotation tries to solve is to define the expected parameter types of the consumer closure. The generics type defined in Closure<R> correspond to the result type of the closure, but tell nothing about what the closure must accept as arguments.

There's no way in Java or Groovy to express the type signature of the expected closure call method from outside the closure itself, so we rely on an annotation here. Unfortunately, annotations also have limitations (like not being able to use generics placeholder as annotation values) that prevent us from expressing the type directly.

Additionally, closures are polymorphic. This means that a single closure can be used with different, valid, parameter signatures. A typical use case can be found when a closure accepts either a Entry or a (key,value) pair, like the DefaultGroovyMethods.each method.

For those reasons, the ClosureParams annotation takes these arguments:

As a result, the previous signature can be written like this:

public <T,R> List<R> doSomething(List<T> source, @ClosureParams(FirstParam.FirstGenericType.class) Closure<R> consumer)

Which uses the FirstParam.FirstGenericType first generic type of the first argument

hint to tell that the only expected argument type corresponds to the type of the first generic argument type of the first method parameter.

Element Summary

Required Element Summary
Type Name and Description
Class<? extends ClosureSignatureHint> value
Optional Element Summary
Type Name and Description
Class<? extends ClosureSignatureConflictResolver> conflictResolutionStrategy
Default:
ClosureSignatureConflictResolver.class
String[] options
Default:
{}

Inherited Methods Summary

Inherited Methods
Methods inherited from class Name
class Object wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll

Element Detail

public Class<? extends ClosureSignatureConflictResolver> conflictResolutionStrategy

Default:
ClosureSignatureConflictResolver.class

public String[] options

Default:
{}

public Class<? extends ClosureSignatureHint> value

© 2003-2020 The Apache Software Foundation
Licensed under the Apache license.
https://docs.groovy-lang.org/3.0.7/html/gapi/groovy/transform/stc/ClosureParams.html