java反射检测参数的某个字段不能为空

本文探讨了Java反射机制在参数校验中的应用,通过实现参数匹配映射表和自定义校验方法,确保参数的有效性和一致性。具体展示了如何通过反射获取类属性并进行非空验证,以提升代码的健壮性和灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
*
* @author 0414
*
*/
public class TestReflectChecker {

public class Param {
private String id;

private String name;

private String year;

private String month;

private String day;

public Param() {}

public String getDay() {
return day;
}

public void setDay(String day) {
this.day = day;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getMonth() {
return month;
}

public void setMonth(String month) {
this.month = month;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getYear() {
return year;
}

public void setYear(String year) {
this.year = year;
}
}

/**
* CHECK_FIELD
*/
private enum CHECK_FIELD {
id,

name,

year,

month,

day
}

private static Map<String, CHECK_FIELD[]> matchMap = new HashMap<String, CHECK_FIELD[]>();

static {
//id 1 : name is not null;
matchMap.put("1",
new CHECK_FIELD[] { CHECK_FIELD.id, CHECK_FIELD.name });

//id 2 : year, month, day is not null;
matchMap.put("2", new CHECK_FIELD[] { CHECK_FIELD.id, CHECK_FIELD.year,
CHECK_FIELD.month, CHECK_FIELD.day });
}

private TestReflectChecker() {

}

/**
* パラメータをチェック
*
* @param param
* @return
*/
public static boolean check(Param param) {
if (param == null) {
return false;
}

String id = param.getId();

CHECK_FIELD[] checkFields = matchMap.get(id);

if (checkFields == null) {
return false;
}

for (CHECK_FIELD field : checkFields) {
Method getFieldMethod = getGetMehtodByField(Param.class, field
.toString());
try {
Object value = getFieldMethod.invoke(param, new Object[] {});
if (value == null) {
System.out.println(field + " is null, false will be return .");
return false;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

return true;
}

/**
* fieldからmethodを取得
*
* @param clazz
* @param field
* @return
*/
private static Method getGetMehtodByField(Class clazz, String field) {
Method method = null;

String methodName = "get" + field.substring(0, 1).toUpperCase()
+ field.substring(1);
try {
method = clazz.getMethod(methodName, new Class[] {});
} catch (Exception e) {
e.printStackTrace();
}
return method;
}

public static void main(String[] args) {
Param param = new TestReflectChecker().new Param();
param.setId("1");
param.setName("name");
System.out.println(TestReflectChecker.check(param));

param.setId("2");
param.setYear("2011");
System.out.println(TestReflectChecker.check(param));
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值