一、创建一个自定义注解
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.METHOD}) @Documented public @interface IsItNecessary { boolean key() default false; }
二、建立一个实体类
@IsItNecessary(key =true) //必传参数 private String mappingId; @IsItNecessary(key =true) private String companyId; private String membershipCard; private String membershipCardNum; private String userName; @IsItNecessary(key =true) private String mobilePhone; private String mappingId; @IsItNecessary(key =true) private String companyId; private String membershipCard; private String membershipCardNum; private String userName; @IsItNecessary(key =true) private String mobilePhone;
三、通过java反射拿到实体类参数
public static void isAllFieldNull(Object obj) throws Exception{
Class stuCla = (Class) obj.getClass();// 得到类对象
Field[] fs = stuCla.getDeclaredFields();//得到属性集合
boolean flag = true;
boolean r =false;
for (Field f : fs) {//遍历属性
f.setAccessible(true); // 设置属性是可以访问的(私有的也可以)
Object val = f.get(obj);// 得到此属性的值
IsItNecessary t = (IsItNecessary) f.getAnnotation(IsItNecessary.class);
if(t != null) {
r = t.key();
if (r == false) {
continue;
}
if (val != null) {//只要有1个属性不为空,那么就不是所有的属性值都为空
System.out.println("属性" + f.getName() + "值为:" + val);
} else {
System.out.println("属性" + f.getName() + ",不能为空");
}
}
}
}
最后测试
public static void main( String[] args ) { GsUser gsUser = new GsUser(); try { isAllFieldNull(gsUser); } catch (Exception e) { e.printStackTrace(); } }运行结果:
未完待续!!!!