Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to put annotation after access modifier in Java 7? Or Java 8?

This is usual code:

@Autowire
private Service service;

But with Java 7 this also works (and shorter):

private @Autowire Service service;

Is that legal in Java 8 (have same semantic)? Is that bad coding practice?

like image 743
gavenkoa Avatar asked Apr 03 '14 13:04

gavenkoa


People also ask

What are the applicable rules on Java access modifier?

Protected Access Modifier - Protected Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class. The protected access modifier cannot be applied to class and interfaces.

Where are annotations allowed Java?

The 3 values that the @Retention annotation can have: SOURCE: Annotations will be retained at the source level and ignored by the compiler. CLASS: Annotations will be retained at compile-time and ignored by the JVM. RUNTIME: These will be retained at runtime.

Which is the most restrictive access modifier in Java?

Private. Any method, property or constructor with the private keyword is accessible from the same class only. This is the most restrictive access modifier and is core to the concept of encapsulation.

Are Java modifiers friendly?

There isn't a friendly modifier in Java. In Java it is called package private. And it is the default modifier.


1 Answers

According to documentation

In Java 7 :

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements. When used on a declaration, each annotation often appears, by convention, on its own line.

As of the Java SE 8 release, annotations can also be applied to the use of types. :

Class instance creation expression:

new @Interned MyObject();

Type cast:

myString = (@NonNull String) str;

implements clause:

class UnmodifiableList<T> implements
    @Readonly List<@Readonly T> { ... }

Thrown exception declaration:

void monitorTemperature() throws
    @Critical TemperatureException { ... }
like image 108
user987339 Avatar answered Oct 17 '22 07:10

user987339