gpt4 book ai didi

java - Spring方面如何跨多个对象更新公共(public)字段

转载 作者:太空宇宙 更新时间:2023-11-04 09:09:45 25 4
gpt4 key购买 nike

我正在编写 Spring 方面并寻找一种方法来更新返回对象上的字段

我的Dto

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class BaseDto{
LocalDateTime testTime;
}

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class TestDto{
private BaseDto baseDtol
}

@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class SampleDto{
private BaseDto baseDtol
}

我的转换器类:

@TestAnnotation
public TestDto covert(){
return new TestDto()
}

@TestAnnotation
public SampleDto covert(){
return new SampleDto()
}

方面:

@Aspect
@Component
public class TestAspect {
@AfterReturning(value = "@annotation(TestAnnotation)", returning = "entity")
public void test(JoinPoint joinPoint, Object entity){
//Looking for a way to set BaseDto in the TestDto and SampleDto objects
}
}

我的方面将从转换器类调用,返回对象可以是 SampleDto 和 TestDto。我正在寻找一种在其中设置 BaseDto 对象的方法。

最佳答案

已编辑

您可以使用java反射动态地将BaseDto对象设置为entity字段。

1- Iterate through fields of entity.

  • Check fields type (must equal to BaseDto.class)

2- set accessibility of the checked field to true.

3- set new BaseDto() to field.

@AfterReturning(pointcut = "servicePointCut()", returning = "entity")
public void afterReturningAdvice(JoinPoint joinPoint, Object entity) throws IllegalAccessException

{

//Iterate through fields of entity
for (Field field : entity.getClass().getDeclaredFields()) {

//Check type of field (equals to BaseDto.class)
if (field.getType().equals(BaseDto.class)) {

//Set accessibility of field to true
field.setAccessible(true);

//Set new BaseDto to entityobject
BaseDto baseDto = new BaseDto();
field.set(entity, baseDto);
}

}

//Rest of afterReturningAdvice method ...
}

关于java - Spring方面如何跨多个对象更新公共(public)字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59794092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com