泛型必须要有<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){标签:反射,BaseBindCardResponseDto,String,errorCodeField,responseDto,泛型,tClass,public,赋值 From: https://www.cnblogs.com/catcatsmall/p/16634852.html
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;
}