I found several related (not duplicate) question to this, but they didn't satisfy me.
I am unable to understand where and why to use custom annotations
?
I read an example of custom annotation in a book, but it was not explained thoroughly.
@interface MyAnno { String str(); int val(); } class MyClass { @MyAnno(str = "Annotation example", val = 100) public static void myMeth() { System.out.println("Inside myMeth()"); } } class CustomAnno { public static void main(String args[]) { MyClass.myMeth(); } }
The output is as expected Inside myMeth()
.
I am having few questions regarding this example.
1- How can I use
String str()
andint val()
in this program? ORWhat is the use of any abstract method of an
custom annotation
?2- Why
custom annotations
. I mean that what effect they are having on any code.3- How can I create an annotation which is having effects like @override is having?(I mean any kind of effect which can be noticed)
If this example is useless for you, then please give me a suitable small example in which a custom annotation
is used.
Java annotations are a mechanism for adding metadata information to our source code. They're a powerful part of Java that was added in JDK5. Annotations offer an alternative to the use of XML descriptors and marker interfaces.
Annotations have a number of uses, among them: Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings. Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
Java annotations are metadata (data about data) for our program source code. They provide additional information about the program to the compiler but are not part of the program itself. These annotations do not affect the execution of the compiled program.
Three main reasons to use custom annotations are:
In each case, use of annotations reduces the likelihood of errors in your code, compared to other non-annotation approaches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With