java Annotation Demo
Java 1.5引入了annotation,这个功能非常好用,是用c#等语言借鉴过来的一个特性。
首先编译器本身支持一些像overrides,supresswarning之类的注解。
Spring,junit等框架也自己写并且处理自己定义的注解,让java具有了一些声明式编程的一些特点,而且减少了代码量。
下面的示例是一个简单的自定义注解,自定义的注释的处理需要自己去维护。
下面的应用写得不好,例如在web编程中,我们可以根据java bean的一些fields的注解,自动生成相应的Structs验证标签之类的
可以更快捷地完成jsp页面的开发。
import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Field; import java.util.regex.Pattern; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface EmailAddress { } class student { String sname; int sid; @EmailAddress String email; public student(int _sid, String _sname, String _email) { sid = _sid; sname = _sname; email = _email; } public String toString() { return "id:" + sid + "sname:" + sname + " email:" + email; } } class emailValidator { static boolean isvalidemail(String email) { Pattern ptn = Pattern .compile("^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"); return ptn.matcher(email).matches(); } public static void checkEmailType(Object obj, Class<? extends Annotation> antcls) throws IllegalArgumentException, IllegalAccessException { Class<?> cls = obj.getClass(); for (Field field : cls.getDeclaredFields()) { if (field.isAnnotationPresent(antcls)) { if (antcls.isAssignableFrom(EmailAddress.class)) { if (!isvalidemail(field.get(obj).toString())) { try { System.out.println("Anotation " + antcls.getName() + " validate is not pass for value:" + "class " + obj.getClass().getName() + " field " + field.getName() + ":" + field.get(obj).toString()); } catch (Exception e) { e.printStackTrace(); } } } } } } } public class testAnnotation { public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException { student s = new student(1, "yaoshuya", "yaoshuya@ss.dd.dfd..com"); System.out.println(student.class.isAssignableFrom(s.getClass())); emailValidator.checkEmailType(s, EmailAddress.class); // System.out.println(emailValidator.isvalidemail(s.email)); } }
Looking for a job working at Home about MSBI