Home > Mobile >  What is type level annotation?
What is type level annotation?

Time:07-25

What is a type level annotation?

I was reading the doc of @TestInstance and there it is written that it is a type-level annotation.

CodePudding user response:

This is not an official term - it doesn't appear in the Java Language Specification. But we can still understand what it means by combining the meaning of the three words "type", "level" and "annotation".

A "type level annotation" is an annotation applied at the type level (in other words, on a type), rather than, say, at the method level.

@TestInstance(LifeCycle.PER_CLASS) // applied to the class
class MyTest {
    // @TestInstance(LifeCycle.PER_CLASS) // should not annotate a method with this
    @Test
    public void fooWorks() { ... }
}

This is also suggested by the @Target annotation present on TestInstance:

@Target(value=TYPE)

The parameter is ElementType.TYPE, which limits the annotation's target to the following things:

Class, interface (including annotation interface), enum, or record declaration

These stack overflow posts (1, 2, 3) also use "type level annotation" in this way. I also found this page which uses the terms "method level" and "field level" annotations, which follows a similar logic.

Basically, you can think of "X-level annotation" as "this annotation marks an X", which in turn means "X is one of the things in the annotation's @Target meta-annotation".


Note that "type level annotation" should not be confused with "type annotation", a term that does appear in the JLS. A "type annotation" is one that can annotate the use of a type (corresponds to ElementType.TYPE_USE), as opposed to declarations.

CodePudding user response:

A "type-level annotation" is an annotation, which is applied to a type. The documentation of ElementType.TYPE defines it as follow:

public static final ElementType TYPE

Class, interface (including annotation type), or enum declaration

So you write this @TestInstance annotation most likely for your test suite class.

  • Related