What is the purpose of annotations in Java?

annotations, java

Solution

Annotations are metadata. `@Override` annotation is used to make sure that you are overriding method of a superclass and not just making a method with the same name. Common mistakes here consist of:

- spelling the method's name wrong `equal(Object o)` instead of `equals(Object o)`

putting different set of arguments

MyString extends String { public boolean equals(MyString str) {} }

`equals(MyString str)` is not overriding the method `equals(Object o)` and therefore will not be used by standard Java comparators (which is used in some standard functions, such as `List.contains()` and this is prone to error situation). This annotation helps compiler to ensure that you code everything correctly and in this way it helps program.

`@Deprecated` annotation doesn't make program not to compile but it makes developers think about using the code that can and/or will be removed in a future releases. So they (developers) would think about moving onto another (updated) set of functions. And if you compile your program with the flag `-Xlint` compilation process will return with an error unless you remove all usages of deprecated code or explicitly mark them with annotation `@SuppressWarnings("deprecation")`.

`@SuppressWarnings` is used to suppress warnings (yes, I know it's Captain Obvious style :)). There is a deprecation suppression with `@SuppressWarnings("deprecation")`, unsafe type casting with `@SuppressWarnings("unchecked")` and some others. This is helpfull when your project compiler have a compilation flag `-Xlint` and you cannot (or don't want to) change that.

There are also annotation processors that you integrate into your program build process to ensure that program code meets some sort of criteria. For example with IntelliJ Idea IDE annotation processor you can use `@Nullable` and `@NotNull` annotations. They show other programmers when they use your code so that can transfer null as a certain parameter to a method or not. If they transfer null it will cause exception during compilation or before executing a single line method's code.

So annotations are quite helpful if you use them to their full potential.

Problem

I understand that annotations serve a purpose to modify code without actually BEING code, such as: ``` @Author( name = "Benjamin Franklin", date = "3/27/2003" ) ``` But I don't understand how using the annotation is any better/ clearer/ more concise than just saying name = "Benjamin Franklin" ? How does the addition of annotations strengthen the code? EDIT: Sorry for another questoin, but I know that @Override can help prevent/ track spelling mistakes when calling methods or classes, but how does it do that? Does it help the actual program at all?

Original source