一、注解在类上
package annotation5;import annotation4.*;public class ReflectAnnotationTest { public static void main(String[] args) throws Exception { Class c =Class.forName("annotation4.AnnotationTest01"); //判断类上面是否有@annotation4.MyAnnotation //System.out.println(c.isAnnotationPresent(MyAnnotation.class)); if (c.isAnnotationPresent(MyAnnotation.class)){ MyAnnotation myAnnotation = (MyAnnotation) c.getAnnotation(MyAnnotation.class); //获取注解对象的属性 String value = myAnnotation.value(); System.out.println(value); } //判断String类上面是否存在注解 Class StringClass = Class.forName("java.lang.String"); System.out.println(StringClass.isAnnotationPresent(MyAnnotation.class)); }}
二、注解在类方法中
package annotation6;import java.lang.reflect.Method;public class MyAnnotationTest { @MyAnnotation(username = "admin",password = "123") public void doSome(){ } public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException { Class c = Class.forName("annotation6.MyAnnotationTest"); //获取doSome方法 Method doSomeMethord =c.getDeclaredMethod("doSome"); if (doSomeMethord.isAnnotationPresent(MyAnnotation.class)){ MyAnnotation myAnnotation = doSomeMethord.getAnnotation(MyAnnotation.class); System.out.println(myAnnotation.username()); System.out.println(myAnnotation.password()); } }}
三、注解的应用
package annotation7;import java.lang.reflect.Field;public class Test { public static void main(String[] args) throws Exception{ //获取类 Class userClass = Class.forName("annotation7.User"); if (userClass.isAnnotationPresent(Id.class)){ Field[] fields = userClass.getDeclaredFields(); boolean isOk = false; for (Field field : fields){ if ("id".equals(field.getName()) && "int".equals(field.getType().getSimpleName())){ isOk = true; break; } } //判断是否合法 if (!isOk){ throw new HasNotIdPropertyException("被Id注解标注的类中必须要有一个int类型的id属性"); } } }}
package annotation7;@Idpublic class User { String name;}
package annotation7;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)public @interface Id {}
package annotation7;public class HasNotIdPropertyException extends RuntimeException { public HasNotIdPropertyException() { } public HasNotIdPropertyException(String message) { super(message); }}