Sunday, October 28, 2018

Java Annotations

Annotations are metadata about a program. Annotations will not have a direct effect on the operation of code they annotate.

An annotation looks like the following 

@Test

@ symbol indicates the compiler that the text followed after @ is an annotation. In the following example Author is the annotation name.

@Author(
   name = "Thetestbook.com",
   date = "12/19/2015"
) 
class AnnotationTest() { ... } 

What are the possible ways of applying annotations.

Annotations can be applied in many places like class, method, field and other program elements.

eg:
 myString = (@NonNull String) refStr;
Here @NotNull is an annotation to make sure the typecast string will not be null.

@Readonly is another useful annotation to create read only lists.


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

Another useful annotation is SuppressWarnings to supress warnings of a method

@SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
   }


Repeating annotations:

There are certain annotation types which will allow you to repeat some events on a timely basis. @Schedule is one of those annotations which is very useful in scheduling some events.

@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }
The above example will schedule the method run on last day of the month and also on Friday 11 PM every week. These kind of annotations are very useful in a production environment to cleanup / purge some files and unwanted data which will pile up during the processing.
@Alert(role="Manager")
@Alert(role="Administrator")
public class UnauthorizedAccessException extends SecurityException { ... }
The above code will alert the users with Manager role and Administrator role of the application when a securityException occurs. This will be useful to notify people when an unauthorized person try to access the application. They can take the necessary action on time because of the notifications.

No comments:

Post a Comment