Close

Java - How to get annotation on explicit receiver parameter using reflection?

[Last Updated: Jun 22, 2017]

Java Annotations Java Reflection 

Explicit receiver parameter is a new feature introduced in Java 8.

This example demonstrate how to access type annotations on the receiver type.

package com.logicbig.example;


import java.lang.annotation.*;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Calculator {
public Object calc (@ServerObject Calculator this) {
return null;
}

public static void main (String[] args) throws NoSuchMethodException {
Method m = Calculator.class.getDeclaredMethod("calc");
AnnotatedType aType = m.getAnnotatedReceiverType();
for (Annotation a : aType.getDeclaredAnnotations()) {
System.out.println(a);
}
}

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


Output:

@com.logicbig.example.Calculator$ServerObject()

See Also