How to Create a Custom Annotations?Read full article from
annotations are interfaces, so you don't implement anything in them.
How to Make Use of Your Custom Annotations?
Creating Custom Annotations and Making Use of Them
public @interface Copyright {
String info() default "";
}
Since we didn't define any @Target , you can use this annotation anywhere in your classes by default. If you want your annotation to be only available for class-wise or method-wise, you should define @Target annotation. annotations are interfaces, so you don't implement anything in them.
How to Make Use of Your Custom Annotations?
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {
Class expected();
}
@Retention marks our annotation to be retained by JVM at runtime. This will allow us to use Java reflections later on.Test test = method.getAnnotation(Test.class);
// we use Class type here because our attribute type
// is class. If it would be string, you'd use string
Class expected = test.expected();
try {
method.invoke(null);
pass++;
} catch (Exception e) {
if (Exception.class != expected) {
fail++;
} else {
pass++;
}
}
Creating Custom Annotations and Making Use of Them
No comments:
Post a Comment