DEV Community

Calin Baenen
Calin Baenen

Posted on

Explain Java annotations and how to use them like I'm 5.

I know a popular one is @Override, but other times, when defining an interface I see @interface Name { /* ... */ }.
And sometimes I see random annotations I don't even know (the only one I know is @Override).

Can someone please teach my what these are, how to use them, etc...?

Thanks!
Cheers!

Top comments (5)

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Annotations are a newer way to enhance Java code. Some annotations are applied at compile time (this is the default) - the annotation is no longer available at run time.

For example, with @Override, the compiler will make sure your method really is overriding code in a superclass/interface. If you rename the method in the base class but not in the sub class, the compiler will complain. Without the annotation, the compiler won't give you an error in this case.

You can also mark an annotation to remain in the code at run time. This allows some other code to use reflection to pick up code marked with the relevant annotations. For example, it can be used to inject dependencies into code at run time, as per the Spring framework.

The @interface is special as you would use it to create your own annotations.

Collapse
 
baenencalin profile image
Calin Baenen

What does making your own annotations do?
Are they similar to annotations in Python, or....?

Collapse
 
nestedsoftware profile image
Nested Software • Edited

Here is an example of a compile time custom annotation that automatically generates custom builders for classes that you annotate:

baeldung.com/java-annotation-proce...

Here is an example of a run time custom annotation that is used to convert objects to json:

baeldung.com/java-custom-annotation

I'd say in practice it's fairly rare for application developers to write custom annotations. It's more common to use annotations that are either part of Java itself, or part of some 3rd-party library or framework.

They look a lot like Java annotations, but I think Python decorators are quite a bit simpler than the Java annotations - you are just wrapping some additional code around a class, method, or function at run time. When you call a method wrapped by a decorator, the decorator will be applied directly, whereas I don't believe that is the case for annotations in Java. However, I guess decorators can be used in kind of a similar way to run time annotations in Java. Decorators in python:

realpython.com/primer-on-python-de...

Thread Thread
 
baenencalin profile image
Calin Baenen

Thanks for the resources, helps a lot in my understanding in the language!

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Unfortunately I can't explain annotations the "LI5 way", but I've learned how powerful they are when I started to use Lombok in my Java projects.