Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an annotation type without a @Target be used anywhere?

The Java Tutorials says what follows:

If an @Target meta-annotation is not present on an annotation type T , then an annotation of type T may be written as a modifier for any declaration except a type parameter declaration.

https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/annotation/Target.html

Other manuals says that if @Target is not present an annotation can be used in any place except TYPE_USE or TYPE_PARAMETER scenarios.

I'm not really sure about what "parameter declaration" means in that case. This class compiles, and the annotation "@EveryWhere" is present really everywhere, without any @Target annotation. Including cast operations, lambda parameters and generics declarations.

import java.util.ArrayList;
import java.util.function.Predicate;
@interface EveryWhere{}
public @EveryWhere class  AnnotedEveryWhere<@EveryWhere T> extends @EveryWhere Object{
    @EveryWhere int i = 0;
    @EveryWhere <@EveryWhere T> String method(@EveryWhere ArrayList<@EveryWhere String> array) {
        @EveryWhere Predicate<@EveryWhere ArrayList<@EveryWhere String>> pred = 
                (@EveryWhere ArrayList<@EveryWhere String> lambdaParameter)->{
                    @EveryWhere ArrayList<@EveryWhere String> insideLambda = new @EveryWhere ArrayList<@EveryWhere String>(); 
                    return (@EveryWhere boolean) true;};
        return (@EveryWhere String) "String";
    }

}
like image 807
Marco Olivi Avatar asked Sep 21 '25 08:09

Marco Olivi


1 Answers

It depends on Java version. Java SE 18 says

If an @Target meta-annotation is not present on an annotation interface T, then an annotation of type T may be written as a modifier for any declaration.

Unfortunately https://javaalmanac.io does not do diffs at the level of detail necessary to find out in which version it changed.

like image 189
Tom Hawtin - tackline Avatar answered Sep 22 '25 20:09

Tom Hawtin - tackline