参考:https://zhuanlan.zhihu.com/p/60730622
CheckAge.java
package com.hmb; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface CheckAge { int min() default 0; int max() default 100; }
InitSex.java
package com.hmb; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface InitSex { enum SEX_TYPE { MAN, WOMAN}; SEX_TYPE sex() default SEX_TYPE.MAN; }
People.java
package com.hmb; public class People { @CheckAge() private int age; @InitSex() private String sex; public People(int age, String sex) { this.age = age; this.sex = sex; } public People() { } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
Children.java
package com.hmb; public class Children extends People { @CheckAge(max = 18) private int age; public void setAge(int age) { this.age = age; } }
Main.java
package com.hmb; import java.lang.reflect.Field; public class Main { static void initSex(People people) { Field[] fields = People.class.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(InitSex.class)) { InitSex sex = field.getAnnotation(InitSex.class); try { field.setAccessible(true); field.set(people, sex.sex().toString()); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println("finished init sex"); } } } static boolean checkAge(People people) { Field[] fields = People.class.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(CheckAge.class)) { CheckAge checkAge = field.getAnnotation(CheckAge.class); try { field.setAccessible(true); int age = (int) field.get(people); if (age < checkAge.min() || age > checkAge.max()) { return false; } return true; } catch (IllegalAccessException e) { e.printStackTrace(); } } } return false; } public static void main(String[] args) { People people = new People(); System.out.println(people.getSex()); initSex(people); System.out.println(people.getSex()); people.setAge(-1); System.out.println(checkAge(people)); people.setAge(101); System.out.println(checkAge(people)); people.setAge(20); System.out.println(checkAge(people)); System.out.println("=============="); Children children = new Children(); children.setAge(-1); System.out.println(checkAge(children)); children.setAge(19); System.out.println(checkAge(children)); children.setAge(7); System.out.println(checkAge(children)); } }
标签:java,people,demo,age,People,sex,public,Annotation From: https://www.cnblogs.com/hemeiwolong/p/17478776.html