● 获取class的三种当时
○ 对象.getClass()
○ 类名.class
○ Class.forName(“”)
● getName
● getDeclaredFields 返回值 Field[]
○ filed.set(对象,value) 设置值
○ filed.setAccessible()//暴力破解私有属性,是私有属性能设置值
● getDeclaredMethods 返回值 Method[]
○ 对象.方法名()以前 调用对象的方法
○ method.invoke(对象,参数) 现在 调用对象的方法
○
●
● 实体类
package cn.zhy.spring_04.entiity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private Integer id;
private String username;
private String sex;
private String creatBy;
public void study(){
System.out.println("我在学习");
}
}
● 利用反射给属性设置值
@Component
@Aspect
public class LogInterceptor {
@Pointcut("execution( * cn.zhy.spring_04.service..*.insert*(..))")
public void myMethod() {
// 假设这个方法就是被代理的方法
}
@Before("myMethod()")
public void beforeMethod(JoinPoint joinPoint) throws IllegalAccessException {
//获取拦截方法的参数
Object[] args = joinPoint.getArgs();
System.out.println(args);
for (Object arg : args) {
//获取该类
Class<?> aClass = arg.getClass();
// System.out.println(aClass);
//获取该类中的属性
Field[] declaredFields = aClass.getDeclaredFields();
// System.out.println(declaredFields);
for (Field field : declaredFields) {
// System.out.println(field);
//给属性设置值
if(field.getName().equals("creatBy")){
field.setAccessible(true);
field.set(arg,"admin");
}
}
}
System.out.println("方法执行前");
}
@After("myMethod()")
public void afterMethod() {
System.out.println("方法执行后");
}
//在环绕 增强中,我们可以给定一个参数,代表我们获取处理的切入点
@Around("myMethod()")
public void arround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = joinPoint.proceed();
System.out.println("环绕后");
}
}
打印结果
利用反射调用方法
@Test
public void insertStudent() throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// StudentImpl studentImpl = (StudentImpl) context.getBean("studentImpl");
IStudentService bean = context.getBean(IStudentService.class);
Student student1 = new Student();
Class<? extends Student> aClass = student1.getClass();
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
if (declaredMethod.getName().equals("study")){
declaredMethod.invoke(student1);
}
}
// Method study = aClass.getDeclaredMethod("study");
// study.invoke(student1);
student1.setId(1);
student1.setUsername("张三");
student1.setSex("男");
bean.insertStudent(student1);
}
结果