java清空对象值,Java 8从每个字段中删除字符串值,其中“ string”值来自自定义对象...

Note: I am using Swagger/Open API Specs (using springdoc-openapi-ui) and while making POST request all string fields are having default value as "string" which I really wanted to set it to null or space.

Any quick pointer ?

public static Object getObject(Object obj) {

for (Field f : obj.getClass().getFields()) {

f.setAccessible(true);

try {

if (f.get(obj) == "string") {

f.set(obj, null);

}

} catch (IllegalArgumentException | IllegalAccessException e) {

log.error("Error While Setting default values for String");

}

}

return obj;

}

REST endpoints

@GetMapping(value = "/employees")

public ResponseEntity> findEmployees(

EmployeeDto geoDto,

@Parameter(hidden=true) String sort,

@Parameter(hidden=true) String order,

@Parameter(hidden=true) Pageable pageRequest) {

EmployeeDto dto = (EmployeeDto) CommonsUtil.getObject(geoDto);

Page response = countryService..............;

PagedModel model = employeePagedAssembler.toModel(response, countryOutAssembler);

return new ResponseEntity<>(model, HttpStatus.OK);

}

解决方案

You could do it a bit simpler, I guess. If you control EmployeeDto, for example:

@Accessors(chain = true)

@Getter

@Setter

@ToString

static class EmployeeDto {

private String firstname;

private String lastname;

private int age;

}

You could iterate over fields of the class and using MethodHandles invoke the needed setters, when some getters return the string you are interested in (and Strings are compared using equals, not ==). This can even be made into a tiny library. Here is a start:

private static final Lookup LOOKUP = MethodHandles.lookup();

/**

* this computes all the know fields of some class (EmployeeDTO in your case) and their getter/setter

*/

private static final Map, Map>, Entry>> ALL_KNOWN =

Map.of(

EmployeeDto.class, metadata(EmployeeDto.class)

);

private Map> MAP;

/**

* For example this will hold : {"firstname", String.class} -> getter/setter to "firstname"

*/

private static Map>, Entry> metadata(Class> cls) {

return Arrays.stream(cls.getDeclaredFields())

.map(x -> new SimpleEntry<>(x.getName(), x.getType()))

.collect(Collectors.toMap(

Function.identity(),

entry -> {

try {

return new SimpleEntry<>(

LOOKUP.findGetter(cls, entry.getKey(), entry.getValue()),

LOOKUP.findSetter(cls, entry.getKey(), entry.getValue()));

} catch (Throwable t) {

throw new RuntimeException(t);

}

}

));

}

With that information you can provide a public method for users to call, So you need to provide the actual instance of your DTO, the DTO class, the Class of the fields you want to "default to", the equality to check against and the actual defaultValue.

public static T defaulter(T initial,

Class dtoClass,

Class fieldType,

R equality,

R defaultValue) throws Throwable {

Set> all =

ALL_KNOWN.get(dtoClass)

.entrySet()

.stream()

.filter(x -> x.getKey().getValue() == fieldType)

.map(Entry::getValue)

.collect(Collectors.toSet());

for (Entry getterAndSetter : all) {

R whatWeGot = (R) getterAndSetter.getKey().invoke(initial);

if (Objects.equals(whatWeGot, equality)) {

getterAndSetter.getValue().invoke(initial, defaultValue);

}

}

return initial;

}

And this is how your callers can call it:

public static void main(String[] args) throws Throwable {

EmployeeDto employeeDto = new EmployeeDto()

.setFirstname("string")

.setLastname("string");

EmployeeDto withDefaults = defaulter(employeeDto, EmployeeDto.class, String.class, "string", "defaultValue");

System.out.println(withDefaults);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值