通过反射进行对象注入

两个基础的类,在controller中没有new service的对象,接下来注入以后通过get方法获取controller中的对象打印出来,比较对象地址

package com.project.service;

public class ReportService {
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	

}

package com.project.controller;

import com.project.service.ReportService;

public class ReportController {

	private ReportService reportService;

	public ReportService getReportService() {
		return reportService;
	}

	public void setReportService(ReportService reportService) {
		this.reportService = reportService;
	}
	
	
}

注入测试类

package com.project.test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.project.controller.ReportController;
import com.project.service.ReportService;

public class myTest {
	
	public static void main(String[] args) {
		ReportController reportController = new ReportController();
		System.out.println(reportController.getReportService());
		Class<? extends ReportController> class1 = reportController.getClass();
//		创建对象
		ReportService reportService = new ReportService();
		System.out.println(reportService);
		try {
			//获取属性
			Field serviceField = class1.getDeclaredField("reportService");
			//获取权限 访问私有方法
//			serviceField.setAccessible(true);
			//只有通过方法才能设置具体的属性值
			String name = serviceField.getName();
			//拼接方法的名称 一般get或者set的方法都是有规律的 
			name = name.substring(0,1).toUpperCase()+name.substring(1, name.length());
			String setMethodName = "set"+name;
			String getMethodName = "get"+name;
			//通过方法注入对象属性
			Method method = class1.getMethod(setMethodName, ReportService.class);
			//反射
			method.invoke(reportController, reportService);
			System.out.println(reportController.getReportService());
		} catch (NoSuchFieldException | SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

运行结果

null
com.project.service.ReportService@15db9742
com.project.service.ReportService@15db9742

第一个结果为空,那个时候还没有进行注入,所以为空
第二个是new的对象地址
第三个是注入以后获取的值

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值