Reputation: 1805
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.
Upvotes: 26
Views: 15373
Reputation: 151
In my case, I tried using METHOD-level annotations. Below is the code for parsing the annotations.
`public static void main(String[] args) throws Exception {
Framework myFramework = new Framework();
System.out.println("==WithOut-Annotation Parsing==");
myFramework.serviceCall();
System.out.println("==Annotation Parsing==");
myFramework.serviceCallx();
}
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomOne {
String valueOne() default "valueOne";
String valueTwo() default "valueTwo";
}
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomTwo {
String valueThree() default "valueThree";
String valueFour() default "valueFour";
}
public class Service {
@CustomOne(valueOne = "One", valueTwo = "Two")
@CustomTwo(valueThree = "Three", valueFour = "Four")
public void test() {
System.out.println("I am inside Service :: test() method");
}
@CustomOne
@CustomTwo
public void testx() {
System.out.println("I am inside Service :: testx() method");
}
}
public class Framework {
// normal
public void serviceCall() {
Service service = new Service();
service.test();
service.testx();
}
// annotation parsing
public void serviceCallx() throws Exception {
Service service = new Service();
Method method = service.getClass().getMethod("testx"); // give specific method in string format
if (method.isAnnotationPresent(CustomOne.class)) {
CustomOne customOne = method.getAnnotation(CustomOne.class);
System.out.println("Custom One Annotation Parsing : " + customOne.valueOne() + " " + customOne.valueTwo());
}
if (method.isAnnotationPresent(CustomTwo.class)) {
CustomTwo customTwo = method.getAnnotation(CustomTwo.class);
System.out.println("Custom Two Annotation Parsing : " + customTwo.valueThree() + " " + customTwo.valueFour());
}
}
}
`
Upvotes: 0
Reputation: 671
To be of any use, annotations must be parsed first. The built-in annotations (such as @Override
or @FunctionalInterface
, to name the most obvious ones) are parsed by the compiler itself. As for custom annotations, these guys are commonly parsed by third-party frameworks, although we can also use the reflection mechanism to demonstrate this technique in standalone code.
By way of an example, the code below changes its behaviour at run time depending on the value of the field declared in the custom annotation named @SwitchingAnnotation
:
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface SwitchingAnnotation{
boolean flag();
}
public class Worker{
void doThis(){ System.out.println("Doing this"); }
void doThat(){ System.out.println("Doing that"); }
@SwitchingAnnotation(
flag = false
)
public void work(boolean flag) {
if (flag) doThis();
else doThat();
}
}
class Test{
public static void main(String[] args) {
try{
SwitchingAnnotation sw = Worker.class.getMethod("work", boolean.class)
.getAnnotation(SwitchingAnnotation.class);
new Worker().work(sw.flag()); // prints Doing that
}
catch(NoSuchMethodException nsme){
System.out.println(nsme);
}
}
}
Upvotes: 1
Reputation: 8117
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.
Upvotes: 13
Reputation: 1259
Here is a minimal example. The following code demonstrates use of custom annotation.
It is about Employees and Benefits. If we have a requirement such that BasicBenefits has to be applied to all types of employess then we can come up with custom annotation such as BasicBenefits, and annotate all types of Employee implementations (e.g. CorporateEmployee, ContractEmployee, ManagerEmployee etc. etc.) with the BasicBenefits.
Custom Annotation Class(interface)
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface BasicBenefits {
String bId() default "B-101";
String bName() default "General Class A Employee";
}
Class using the custom annotation(no need of any imports):
@BasicBenefits(bId="B-400", bName="General Plus Class A Employee")
public class Employee {
String eId;
String eName;
public Employee(String eId, String eName){
this.eId = eId;
this.eName = eName;
}
public void getEmployeeDetails(){
System.out.println("Employee ID: "+eId);
System.out.println("Employee Name: "+eName);
}
}
Driver class to test out the above.
import java.lang.annotation.Annotation;
public class TestCustomAnnotationBasicBenefits {
public static void main(String[] args) throws Exception{
Employee emp = new Employee("E-100", "user3320018");
emp.getEmployeeDetails();
Class reflectedClass = emp.getClass();
Annotation hopeBenefitAnn = reflectedClass.getAnnotation(BasicBenefits.class);
BasicBenefits bBenefits = (BasicBenefits)hopeBenefitAnn;
System.out.println("Benefit ID: "+bBenefits.bId());
System.out.println("Benefit Name: "+bBenefits.bName());
}
}
Your code look almost there, just two things need to be included in the main method.
1.) Need reference to MyClass 2.) Need to get the annotation using reflection from MyClass.
Here is a bit modified code from what you have:
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno
{
String str();
int val();
}
//using above custom annotation on class level
//can also use method level
//just need to change t @Target(ElementType.METHOD)
@MyAnno(str = "Annotation example", val = 100)
class MyClass
{
public static void myMeth()
{
System.out.println("Inside myMeth()");
}
}
import java.lang.annotation.Annotation;
class CustomAnno
{
public static void main(String args[])
{
//1. getting reference to the class where the custom annotation is applied.
//2. then getting the annotation to get the values
MyClass myClass = new MyClass();
Class cls = myClass.getClass();
Annotation getMyAnno = cls.getAnnotation(MyAnno.class);
MyAnno myAnno = (MyAnno)getMyAnno;
MyClass.myMeth(); //left this as is.
System.out.println("myAnno.str(): "+ myAnno.str());
System.out.println("myAnno.str(): "+ myAnno.val());
}
}
Upvotes: 8
Reputation: 5308
The abstract methods of the annotation define the values you can pass to it (in your case str = "Annotation example", val = 100
). You can access them using reflection (Method.<T>getAnnotation(Class<T>)
). Custom annotations don’t have direct impact. They are only useful if you evaluate them.
Note that you have to annotate your custom annotation with @Retention(value=RUNTIME)
to be able to read it via reflection.
Upvotes: 2