152. Getting the annotation of a receiver type

Starting with JDK 8, we can use explicit receiver parameters. Mainly, this means that we can declare an instance method that takes a parameter of the enclosing type with the this Java keyword.

Via explicit receiver parameters, we can attach type annotations to this. For example, let's assume that we have the following annotation:

@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Ripe {}

Let's use it to annotate this in the eat() method of the Melon class:

public class Melon {
...
public void eat(@Ripe Melon this) {}
...
}

In other words, we can only call the eat() method if the instance of Melon represents a ripe melon:

Melon melon = new Melon("Gac", 2000);

// works only if the melon is ripe
melon.eat();

Getting the annotation on an explicit receiver parameter using reflection can be accomplished via JDK 8 with the java.lang.reflect.Executable.getAnnotatedReceiverType() method. This method is available in the Constructor and Method classes as well, and so we can use it like so:

Class<Melon> clazz = Melon.class;
Method eatMethod = clazz.getDeclaredMethod("eat");

AnnotatedType annotatedType = eatMethod.getAnnotatedReceiverType();

// modern.challenge.Melon
System.out.println("Type: " + annotatedType.getType().getTypeName());

// [@modern.challenge.Ripe()]
System.out.println("Annotations: "
+ Arrays.toString(annotatedType.getAnnotations()));

// [interface java.lang.reflect.AnnotatedType]
System.out.println("Class implementing interfaces: "
+ Arrays.toString(annotatedType.getClass().getInterfaces()));

AnnotatedType annotatedOwnerType
= annotatedType.getAnnotatedOwnerType();

// null
System.out.println(" Annotated owner type: " + annotatedOwnerType);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.35.255