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

泛型的具体使用以及反射赋值
泛型必须要有 不然编译报错

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;
}

你可能感兴趣的:(java,开发语言)