Skip to content

Instantly share code, notes, and snippets.

@cassc
Created April 9, 2014 08:16
Show Gist options
  • Save cassc/10240272 to your computer and use it in GitHub Desktop.
Save cassc/10240272 to your computer and use it in GitHub Desktop.
Java Annotation basics
/*
* 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