文章内容
1、定义Autowired注解
01 02 03 04 05 06 07 08 09 10 11 | package com.ntan520.reflect; 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 Autowired { } |
2、定义一个service
1 2 3 4 | package com.ntan520.reflect; public class PersonService { } |
3、定义一个controller
01 02 03 04 05 06 07 08 09 10 11 | package com.ntan520.reflect; public class PersonController { @Autowired private PersonService personService; public PersonService getPersonService() { return personService; } } |
4、实现Autowired
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package com.ntan520.reflect; import java.lang.reflect.Field; public class TestAutowired { public static void main(String[] args) throws Exception { PersonController personController = new PersonController(); Class<? extends PersonController> clazz = personController.getClass(); //获取所有的属性值 Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { String fieldName = field.getName(); System.out.println( "fieldName:" + fieldName); Autowired annotation = field.getAnnotation(Autowired. class ); //判断当前属性是否有Autowired这个注解 if ( null != annotation) { //设置属性可以访问 field.setAccessible( true ); //获取属性类型 Class<?> type = field.getType(); //通过属性类型创建实例 Object o = type.newInstance(); //把创建好的实例对象设置到controller上 field.set(personController, o); } } System.out.println(personController.getPersonService()); } } |
5、输出日志
1 2 3 | // 打印结果 fieldName:personService com.ntan520.reflect.PersonService@63947c6b |