package zhujie;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)//此注解只能使用在类上
@Retention(RetentionPolicy.RUNTIME)//此注解存储在class文件中并且可以被反射机制读取
public @interface Id {
String value() default "China";
int id();
}
package zhujie;
import java.lang.reflect.Field;
@Id
public class AnnotationTset {
int id;
String name;
double height;
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("zhujie.AnnotationTset");
Field[] declaredFields = aClass.getDeclaredFields();
boolean isOK=false;
for (Field f:declaredFields
) {
if("int".equals(f.getType().getSimpleName())&&"id".equals(f.getName())){
isOK=true;
}
}
if(!isOK){
throw new Exception("被注解的类中不含id整个属性或者id这个属性的类型不是int");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package zhujie;
public class Exception extends java.lang.Exception {
public Exception(){
}
public Exception(String message) {
super(message);
}
}
获取注解的属性值
package zhujie;
import java.lang.reflect.Field;
@Id(id=10)
public class AnnotationTset {
int id;
String name;
double height;
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("zhujie.AnnotationTset");
boolean annotationPresent = aClass.isAnnotationPresent(Id.class);
System.out.println(annotationPresent);
if(annotationPresent){
Id annotation = aClass.getAnnotation(Id.class);
System.out.println(annotation.value());
System.out.println(annotation.id());
}
Field[] declaredFields = aClass.getDeclaredFields();
boolean isOK=false;
for (Field f:declaredFields
) {
if("int".equals(f.getType().getSimpleName())&&"id".equals(f.getName())){
isOK=true;
}
}
if(!isOK){
throw new Exception("被注解的类中不含id整个属性或者id这个属性的类型不是int");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}