泛型的具体使用以及反射赋值

泛型必须要有<T> 不然编译报错
T responseDto, Class<T> tClass这个必须是同一个类传过来
public class BindCardHelperTest {
public static void main(String[] args) {
BaseBindCardResponseDto responseDto = new BaseBindCardResponseDto();
Integer status = 1;
responseDto.setStatus(status);
responseDto.setSuccess(true);
BaseBindCardResponseDto dto = setFalseResponseDto(responseDto, BaseBindCardResponseDto.class, "False", "错错错");
System.out.println(dto);
}
}
public static <T> T setFalseResponseDto(T responseDto, Class<T> tClass, String errorCode, String errorMsg){
try {
Field errorCodeField = tClass.getDeclaredField("errorCode");
Field errorMsgField = tClass.getDeclaredField("errorMsg");
errorCodeField.setAccessible(true);
       //允许更改私有字段
errorMsgField.setAccessible(true);
       //给属性赋值
errorCodeField.set(responseDto, errorCode);
errorMsgField.set(responseDto, errorMsg);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
return responseDto;
}
posted @ 2022-08-29 09:42  宁山  阅读(140)  评论(0)    收藏  举报