@interface反射赋值

定义一个Autowired接口

package com.biaodian.myface;

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 {
}

定义两个service

package com.biaodian.service;

public class HelloService {
}




package com.biaodian.service;

public class UserService {
}

定义一个controller

package com.biaodian.controller;

import com.biaodian.myface.Autowired;
import com.biaodian.service.HelloService;
import com.biaodian.service.UserService;

public class HelloController {
    @Autowired
    private HelloService helloService;

    @Autowired
    private UserService userService;

    public HelloService getHelloService() {
        return helloService;
    }
    public UserService getUserService() {
        return userService;
    }
}

在main方法赋值

import com.biaodian.controller.HelloController;
import com.biaodian.myface.Autowired;

import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        //先获取类的class
        Class<HelloController> helloControllerClass = HelloController.class;
        //根据class生产类对象
        HelloController helloController = helloControllerClass.newInstance();
        //获取class的属性遍历
        for (Field declaredField : helloControllerClass.getDeclaredFields()) {
            //判断属性上是否有Autowired注解
            Autowired annotation = declaredField.getAnnotation(Autowired.class);
            if (annotation!=null){
                //私有属性时也可访问
                declaredField.setAccessible(true);
                //有,先获取该属性的class
                Class<?> type = declaredField.getType();
                //根据class获取类对象
                Object o = type.newInstance();
                //把该对象设置到helloController中
                declaredField.set(helloController,o);
            }
        }
        System.out.println(helloController.getUserService());
        System.out.println(helloController.getHelloService());
    }
}

输出打印结果


com.biaodian.service.UserService@511d50c0
com.biaodian.service.HelloService@60e53b93

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值