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

Element Types: Primitives, Strings, and Classes

Understand which types are valid for annotation elements: primitives, String, Class, enums, other annotations, and arrays.

Element Types: Primitives, Strings, and Classes

You'll learn which types are legal for annotation elements and why Java restricts these choices.

What Types Can Annotation Elements Have?

When you define an annotation with @interface, you can't just use any type for its elements. Java only allows a specific set of types, ensuring annotations remain simple, serializable, and safely processable at compile-time and runtime.

The Legal Types

Annotation elements can be:

  1. Primitives: int, long, double, boolean, byte, short, float, char
  2. String: Text values
  3. Class: References to class types (e.g., Class<?> or Class<String>)
  4. Enums: Any enum type
  5. Other annotations: Nested annotation types
  6. Arrays: One-dimensional arrays of any of the above types

Why These Restrictions?

Think of annotations as structured metadata labels attached to your code—they're not full-fledged objects with behavior. Java restricts element types to those that are constant, compile-time safe, and easily representable in bytecode. You can't use List, Map, or custom objects because they introduce complexity and runtime state that annotations weren't designed to handle.

Examples of Valid Element Types

@interface Config {
    int timeout();              // primitive
    String name();              // String
    Class<?> handler();         // Class reference
    int[] ports();              // array of primitives
}

These types work because they're immutable, have literal representations, and can be embedded directly into class files during compilation.

Key Takeaway:
Annotation elements can only use primitives, String, Class, enums, other annotations, and one-dimensional arrays of these types—ensuring annotations remain simple, constant metadata rather than complex runtime objects.