Created
April 9, 2014 08:16
-
-
Save cassc/10240272 to your computer and use it in GitHub Desktop.
Java Annotation basics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Basic usage of Java annotation | |
*/ | |
package test.another; | |
import java.lang.annotation.ElementType; | |
import java.lang.annotation.Retention; | |
import java.lang.annotation.RetentionPolicy; | |
import java.lang.annotation.Target; | |
import java.lang.reflect.Method; | |
public class TestAnnotation { | |
@AnnotInfo(id=13143, info="An ordinary method") | |
public void operate(){ | |
System.out.println("operating"); | |
} | |
public static void main(String[] args) { | |
Method[] methods = TestAnnotation.class.getDeclaredMethods(); | |
for (Method method : methods) { | |
AnnotInfo annot = method.getAnnotation(AnnotInfo.class); | |
if(annot!=null){ | |
System.out.println(method.getName()+" has the annotation: " | |
+annot.getClass().getName()+" " | |
+annot.id()+"/"+annot.info()); | |
} | |
} | |
} | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target(ElementType.METHOD) | |
@interface AnnotInfo{ | |
int id() default 0; // Must NOT contains parameters or throws exception | |
String info(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment