两个基础的类,在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的对象地址
第三个是注入以后获取的值