设为首页 - 加入收藏 焦点技术网
热搜:java
当前位置:首页 >

java注解demo

2014-02-21 15:10:00.0 java  
导读:package org.annation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Retention(RetentionPo...。。。
package org.annation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;




@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotationClass {
public String msg();

}


package org.annation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotationMethod {
public String common();
}


package org.annation;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotationField {


boolean request();
}

package org.annation;


import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class MyAnnotationTest {


public static void main(String[] args) {
MyAnnotationDemo demo = new MyAnnotationDemo();

MyAnnotationClass annotationClass = demo.getClass().getAnnotation(
MyAnnotationClass.class);
System.out.println(annotationClass.msg());


Method method = null;
try {
method = demo.getClass().getMethod("method", new Class[0]);
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
MyAnnotationMethod annotationMethod = method
.getAnnotation(MyAnnotationMethod.class);
System.out.println(annotationMethod.common());



Field field = null;
try {
field = demo.getClass().getDeclaredField("hello");
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
MyAnnotationField annotationField = field
.getAnnotation(MyAnnotationField.class);
System.out.println(annotationField.request());


}
}


(编辑: zpl123456)

网友评论
相关文章