Java反射機制如何解決數(shù)據傳值為空的問題
反射機制數(shù)據傳值為空的問題
兩個小方法,用于解決BeanUtils.copyProperties(x, y);中源對象的值為空問題
1.通過實體注解數(shù)據庫字段為Map的Key,需要的非空值為Value封裝數(shù)據
@Override
? ? public Map<String, Object> setNodeParamItems(DispatchInfoItem dispatchInfoItem) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
? ? ? ? Map<String, Object> map = new HashMap<>();
? ? ? ? DispatchInfo dispatchInfo = new DispatchInfo();
? ? ? ? if (null != dispatchInfoItem) {
? ? ? ? ? ? BeanUtils.copyProperties(dispatchInfoItem, dispatchInfo);
? ? ? ? }
? ? ? ? Method[] methods = dispatchInfo.getClass().getDeclaredMethods();
? ? ? ? if (methods != null) {
? ? ? ? ? ? for (Method method : methods) {
? ? ? ? ? ? ? ? String methodName = method.getName();
? ? ? ? ? ? ? ? if (methodName.startsWith("get")) {
? ? ? ? ? ? ? ? ? ? Column column = dispatchInfo.getClass().getDeclaredMethod(methodName).getAnnotation(Column.class);
? ? ? ? ? ? ? ? ? ? Object value = method.invoke(dispatchInfo);
? ? ? ? ? ? ? ? ? ? if (null != column && StringUtils.isNotBlank(StringHelper.getString(value))) {
? ? ? ? ? ? ? ? ? ? ? ? map.put(column.name(), value);
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return map;
? ? }2.根據獲取的值注入;
public void getMethods(DispatchInfo dispatchInfo, Map<String, Object> map) throws Exception {
? ? ? ? //獲取方法上的注解值
? ? ? ? Method[] methods = dispatchInfo.getClass().getDeclaredMethods();
? ? ? ? if (methods != null) {
? ? ? ? ? ? for (Method method : methods) {
? ? ? ? ? ? ? ? String methodName = method.getName();
? ? ? ? ? ? ? ? if (methodName.startsWith("get")) {
? ? ? ? ? ? ? ? ? ? Column column = dispatchInfo.getClass().getDeclaredMethod(methodName).getAnnotation(Column.class);
? ? ? ? ? ? ? ? ? ? if (column != null) {
? ? ? ? ? ? ? ? ? ? ? ? String setMethodName = methodName.replaceFirst("(get)", "set");
? ? ? ? ? ? ? ? ? ? ? ? Method setMethod = dispatchInfo.getClass().getMethod(setMethodName, method.getReturnType());
? ? ? ? ? ? ? ? ? ? ? ? ;
? ? ? ? ? ? ? ? ? ? ? ? if (null != map.get(column.name())) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? setMethod.invoke(dispatchInfo, map.get(column.name()));
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? }3.根據值進行實際的操作
java 反射 處理 空值
package org.zkdg.utils.spring.annotations.impl;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.sql.SQLException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.zkdg.utils.entity.AjaxEntity;
import org.zkdg.utils.spring.annotations.NNull;
@Aspect
@Component
/**
*
* @author 王海明
* @createData 2017年7月13日 上午8:36:23
* @說明 :出了一些空值。。。
*/
public class AjaxEntityHandler {
// @Pointcut("@annotation(org.zkdg.utils.annotations.AfterHandler)")
@Pointcut("@annotation(org.zkdg.utils.spring.annotations.NullValidate)")
// @Pointcut("execution(* org.dcexam.*.service.*.*(..))")
public void beforeCall() {
// service方法調用之前,檢測參數(shù),僅限第一個參數(shù), 不能為空值
}
/**
* service發(fā)生異常時調用
*/
@Pointcut("execution(* org.dcexam.*.service.*.*(..))")
public void afterThrowEx() {
System.out.println("************\n\n\n\n\n\n\n\n\n\n\n\n*******");
}
@Around(value = "beforeCall()")
public AjaxEntity doBefore(ProceedingJoinPoint point) throws Throwable {
// TODO Auto-generated method stub
// 判斷不能為空
Object[] args = point.getArgs();
if (args == null || args[0] == null) {
return new AjaxEntity("warning", "未選擇任何數(shù)據。。。");
}
// 獲取代理對象類方法參數(shù)
MethodSignature target = (MethodSignature) point.getSignature();
Annotation[][] annotations = target.getMethod().getParameterAnnotations();
int argsIndex = 0;
StringBuilder sb = new StringBuilder();
for (Annotation[] annotation : annotations) {
NNull nn = (NNull) annotation[0];
String[] descs = nn.desc();
String[] fields = nn.field();
if (fields.length > 0 && fields.length > 0 && descs.length == fields.length) {
for (int i = 0; i < fields.length; i++) {
Field field = args[argsIndex].getClass().getDeclaredField(fields[i]);
// 允許訪問
field.setAccessible(true);
Object object = field.get(args[argsIndex]);
if (object == null) {
sb.append(descs[i]).append("不能為空。。。<br>");
}
if (object instanceof String) {
String string = (String) object;
if (string.trim().length() == 0)
sb.append(descs[i]).append("不能為空。。。<br>");
else if (string.trim().equals("0"))
sb.append("未選擇" + descs[i] + "。。。<br>");
} else if (object instanceof Number) {
Integer integer = (Integer) object;
if (integer == 0)
sb.append("未選擇" + descs[i] + "。。。<br>");
}
}
if (sb.length() > 0)
return AjaxEntity.ERROR(sb.toString());
}
argsIndex++;
}
// 加上@Nullvalidate 注解,不允許出現(xiàn)空 值
for (Object obj : args) {
if (obj == null) {
return AjaxEntity.WARNING("出現(xiàn)了不允許的空值");
} else if (obj instanceof String) {
if (((String) obj).length() == 0) {
return AjaxEntity.WARNING("出現(xiàn)了不允許的空值");
}
}
}
AjaxEntity ajax = (AjaxEntity) point.proceed(args);
return ajax == null ? AjaxEntity.ERROR("操作失敗") : ajax;
}
/**
*
* @param joinPoint
* 連接點
* @param ex
* 異常
* @return AjaxEntity 異常信息
*/
@AfterThrowing(value = "afterThrowEx()", throwing = "ex")
public void doAfterThrowEx(JoinPoint joinPoint, Exception ex) {
AjaxEntity ajax = new AjaxEntity();
if (ex.getCause() instanceof SQLException) {
// 數(shù)據庫操作異常
ajax = AjaxEntity.ERROR("操作數(shù)據庫時出現(xiàn)異常");
}
}
}另外,java 命名時 。屬性最好不要有下劃線,否則可能會粗錯。。。。。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
mybatis plus saveBatch方法方法執(zhí)行慢導致接口發(fā)送慢解決分析
這篇文章主要為大家介紹了mybatis plus saveBatch方法導致接口發(fā)送慢解決分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
SpringBoot利用validation實現(xiàn)優(yōu)雅的校驗參數(shù)
數(shù)據的校驗是交互式網站一個不可或缺的功能,如果數(shù)據庫中出現(xiàn)一個非法的郵箱格式,會讓運維人員頭疼不已。本文將介紹如何利用validation來對數(shù)據進行校驗,感興趣的可以跟隨小編一起學習一下2022-06-06
Docker環(huán)境下Spring Boot應用內存飆升分析與解決場景分析
當運行一個Spring Boot項目時,如果未設置JVM內存參數(shù),Spring Boot默認會采用JVM自身默認的配置策略,接下來通過本文給大家介紹Docker環(huán)境下Spring Boot應用內存飆升分析與解決方法,需要的朋友參考下吧2021-08-08
實戰(zhàn)指南:Java編寫Flink?SQL解決難題
想知道如何利用Java編寫Flink?SQL解決難題嗎?本指南將為您揭示最實用的技巧和策略,讓您輕松應對挑戰(zhàn),跟著我們一起探索,讓Java和Flink?SQL成為您問題解決的得力助手!2023-12-12
Docker搭建前端Java的開發(fā)環(huán)境詳解
相信每個人入職第一天就是搭建本地開發(fā)環(huán)境,因為我司用的是java,看見了多年不見的eclipse的圖標出現(xiàn)我的電腦上,我是難過的。后來知道并不是我一個人有此感受。這篇文章是為了解決前后端開發(fā)沒有徹底分離的坑,詳細的給大家介紹了利用Docker搭建前端Java的開發(fā)環(huán)境。2016-10-10

