Dog类:
package com.nick.ref; @MyComponent public class Dog extends Animal { @MyValue("2") private Integer id; @MyValue("旺财") private String name; void shout(){ System.out.println("Dog shout"); } }
类的自定义注解MyComponent:
package com.nick.ref; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) //意思是注解什么时候生效 @Target(ElementType.TYPE) //意思是给谁加注解,类or字段 public @interface MyComponent { }
字段的自定义注解MyValue:
package com.nick.ref; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyValue { String value(); }
注解的反射用法:
package com.nick.ref; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.Arrays; public class TestAnnotation { public static void main(String[] args) throws Exception { Class<Dog> dogClass = Dog.class; MyComponent annotation = dogClass.getAnnotation(MyComponent.class); if (null != annotation){ //创建对象 Constructor<Dog> constructor = dogClass.getConstructor(null); Dog dog = constructor.newInstance(null); //开始赋值 Field[] fields = dogClass.getDeclaredFields(); for (Field field : fields) { MyValue valueAnnotation = field.getAnnotation(MyValue.class); if (null != valueAnnotation){ field.setAccessible(true); String value = valueAnnotation.value(); String typeName = field.getType().getName(); if (typeName.equals("java.lang.Integer")){ field.set(dog, Integer.parseInt(value)); }else { field.set(dog, value); } } } printObject(dog); } } public static void printObject(Object ob) { Field[] fields = ob.getClass().getDeclaredFields();//获取所有属性 String s = ob.getClass().getName(); System.out.print( s.substring( s.lastIndexOf(".")+1 )+ " {"); Arrays.stream(fields).forEach(field -> { //获取是否可访问 boolean flag = field.isAccessible(); try { //设置该属性总是可访问 field.setAccessible(true); System.out.print( field.getName() + "=" + field.get(ob) + ", "); } catch (IllegalAccessException e) { e.printStackTrace(); } //还原可访问权限 field.setAccessible(flag); }); System.out.println("}"); } }