模拟实现Autowired

模拟实现Autowired

package com;

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 {
}
package com;

import com.controller.UserController;
import java.util.stream.Stream;

public class MyTest {

   public static void main(String[] args) throws Exception {
       Class<UserController> cls = UserController.class;
       UserController uc = cls.newInstance();
       Stream.of(cls.getDeclaredFields()).forEach(field -> {
           field.setAccessible(true);
           AutoWired annotation = field.getAnnotation(AutoWired.class);
           if (annotation != null){
               Class<?> type = field.getType();
               try {
                   Object o = type.newInstance();
                   field.set(uc,o);
              } catch (Exception e) {
                   e.printStackTrace();
              }
          }
      });
       System.out.println(uc.getService());
  }
}

 

posted @ 2022-02-01 22:29  Black空我  阅读(138)  评论(0)    收藏  举报