Java的自定义注解使用实例

package test; import java.lang.annotation.Annotation; @Test(age = 15,name = "zhangsan",className = "高三(3)班") public class Person { @Field(name = "lisi") private String name; private int age; public Person() { } @Method(say = "hello") private void say() { System.out.println("Hello,Java Annotation"); } public static void main(String[] args) { boolean hasAnnotation = Person.class.isAnnotationPresent(Test.class); if (hasAnnotation) { Test test = Person.class.getAnnotation(Test.class); System.out.println("age:" + test.age()); System.out.println("name:" + test.name()); System.out.println("className:" + test.className()); } try { java.lang.reflect.Field field = Person.class.getDeclaredField("name"); field.setAccessible(true); Field check = field.getAnnotation(Field.class); if (check != null) { System.out.println("check value:" + check.name()); } java.lang.reflect.Method method = Person.class.getDeclaredMethod("say"); if (method != null) { Annotation[] ans = method.getAnnotations(); for (int i = 0; i < ans.length; i++) { System.out.println("method annotation:" + ans[i].annotationType().getSimpleName()); } } } catch (NoSuchFieldException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/ae8a24b11d77dfdddbf64c6c30869e35.html