Close

Java Reflection - Constructor.getAnnotatedReceiverType() Examples

Java Reflection Java Java API 


Class:

java.lang.reflect.Constructor

java.lang.Objectjava.lang.Objectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AccessibleObjectjava.lang.reflect.AnnotatedElementAnnotatedElementjava.lang.reflect.Executablejava.lang.reflect.Executablejava.lang.reflect.MemberMemberjava.lang.reflect.GenericDeclarationGenericDeclarationjava.lang.reflect.Constructorjava.lang.reflect.ConstructorLogicBig

Method:

public AnnotatedType getAnnotatedReceiverType()

Returns an AnnotatedType object that represents the use of a type to specify the receiver type of the constructor. (see also Java 8 Explicit Receiver Parameters).

For an inner class's constructor, the receiver parameter represents the enclosing class type.


Examples


package com.logicbig.example.constructor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.util.Arrays;

public class GetAnnotatedReceiverTypeExample {
public static class Test {
public class InnerTest {
InnerTest(@Immutable Test Test.this) {}
}
}

@Target({ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
private @interface Immutable {}

public static void main(String... args) throws NoSuchMethodException {
Constructor<Test.InnerTest> c = Test.InnerTest.class.getDeclaredConstructor(Test.class);
AnnotatedType at = c.getAnnotatedReceiverType();
printAnnotatedType(at);

}

private static void printAnnotatedType(AnnotatedType annotatedType) {
print("Type = " + annotatedType.getType().getTypeName());
print("Annotations: " + Arrays.toString(annotatedType.getAnnotations()));
print("Declared Annotations: " + Arrays.toString(annotatedType.getDeclaredAnnotations()));
AnnotatedType annotatedOwnerType = annotatedType.getAnnotatedOwnerType();//Java 9
print("Annotated owner type: " + annotatedOwnerType);
print("AnnotatedType class: " + annotatedType.getClass().getName());
print("AnnotatedType class implementing interfaces: " +
Arrays.toString(annotatedType.getClass().getInterfaces()));
}

private static void print(String string) {
System.out.printf(" %s%n", string);
}
}

Output

  Type = com.logicbig.example.constructor.GetAnnotatedReceiverTypeExample$Test
Annotations: [@com.logicbig.example.constructor.GetAnnotatedReceiverTypeExample$Immutable()]
Declared Annotations: [@com.logicbig.example.constructor.GetAnnotatedReceiverTypeExample$Immutable()]
Annotated owner type: sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@7fbfc286
AnnotatedType class: sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl
AnnotatedType class implementing interfaces: [interface java.lang.reflect.AnnotatedType]




See Also