定义父类
@Data
public class Person {
/**
* 姓名
*/
private String name;
}
定义子类
@Data
@ToString(callSuper = true)
public class Student extends Person {
/**
* 学号
*/
private String studentCode;
}
利用反射给父类属性赋值
public class ReflexTest {
@Test
void test() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
Class<?> stuClass = Class.forName("com.ijunfu.domain.Student");
Student student = (Student) stuClass.getDeclaredConstructor().newInstance();
Class<?> superclass = stuClass.getSuperclass();
Field nameField = superclass.getDeclaredField("name");
nameField.setAccessible(Boolean.TRUE);
nameField.set(student, "ijunfu");
System.out.println(student);
}
}
扩展:使用切面拦截所有Get请求,并给请求中参数的父类赋值
定义切面:
@Aspect
@Component
public class GetRequestAspect {
@Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
if(Objects.nonNull(args) && args.length>0 && args[0] instanceof Person) {
Field nameField = Person.class.getDeclaredField("name");
nameField.setAccessible(Boolean.TRUE);
nameField.set(args[0], "ijunfu");
}
return joinPoint.proceed();
}
}
定义Controller:
@Slf4j
@RestController
@RequestMapping("/student")
public class StudentController {
@GetMapping
public String query(Student student) {
log.warn("{}", student);
return "OK";
}
}
延伸思考:可以设置一些全局性的属性,比如角色是否为admin等