Course contentsShow
← Java
Lesson 2429 of 2,87046. AnnotationsFree lesson

Class-Valued Elements for Type References

Accept Class<?> parameters in annotations to reference types without instantiating them.

Class-Valued Elements for Type References

You'll learn how to use Class<?> as an annotation element type to reference Java types without creating instances.

Why Reference Types in Annotations?

Sometimes your annotation needs to know about a type rather than a value. For example, a validation framework might need to know which exception to throw, or a serialization tool might need a custom handler class. Instead of forcing the user to create instances (wasteful and error-prone), you can accept a Class<?> parameter that simply names the type.

The Core Idea

When you declare an annotation element with type Class<?> (or more specific generics like Class<? extends Exception>), users can pass type references using the .class literal syntax. This gives you metadata about a type without instantiating it.

@interface Validates {
    Class<? extends Throwable> onError();
    Class<?> handlerType() default Object.class;
}

Notice how onError() accepts any subtype of Throwable, while handlerType() accepts any class.

Using the Annotation

@Validates(
    onError = IllegalArgumentException.class,
    handlerType = MyCustomHandler.class
)
public void processData(String input) {
    // Method implementation
}

The user passes type references, not instances. At runtime, you can retrieve these Class objects via reflection and decide what to do—instantiate them, check their properties, or pass them to frameworks.

Why This Matters

This pattern is ubiquitous in frameworks: JPA uses it for entity classes, Spring uses it for component types, and testing libraries use it for expected exception types. It's type-safe, efficient, and avoids unnecessary object creation.

Key Takeaway:
Class-valued annotation elements let you reference types (like MyClass.class) without instantiating them, enabling powerful type-safe metadata in your annotations.