判断某个类是否包含该字段 如果有,则返回结果

判断某个类是否包含该字段 如果有,则返回结果

直接上代码,. 可以直接使用

public static HashMap<String, String> validField(Object field, Object o) throws Exception {
		HashMap<String, String> hashMap = Maps.newHashMap();
		Class class1 = o.getClass();
		Field[] fields = class1.getDeclaredFields();
		String value = null;
		boolean falg = false;
		int index = 0;
		for (int i = 0; i < fields.length; i++) {
			if (fields[i].getName().equals(field)) {
				value = fields[i].getName();
				index = i;
				falg = true;
				break;
			}
		}	
		Object c = null;
		if (falg) {
			Column fieldAnno = fields[index].getAnnotation(Column.class);
             //得到注解属性 值 
            String msg = null;
            if (null != fieldAnno) {
            	 msg = fieldAnno.comment();
			}
			Method method = null;
			method = class1.getMethod(toFieldGetter(value));
			c = method.invoke(o);
			
			hashMap.put("comment", msg);
			hashMap.put("oldValue", c == null ? null : c.toString());
			return hashMap;
		}

		return null;
	}

	public static String toFieldGetter(String fieldname) {
		if (fieldname == null || fieldname.length() == 0) {
			return null;
		}

		/*
		 * If the second char is upper, make 'get' + field name as getter name. For
		 * example, eBlog -> geteBlog
		 */
		if (fieldname.length() > 2) {
			String second = fieldname.substring(1, 2);
			if (second.equals(second.toUpperCase())) {
				return new StringBuffer("get").append(fieldname).toString();
			}
		}

		/* Common situation */
		fieldname = new StringBuffer("get").append(fieldname.substring(0, 1).toUpperCase())
				.append(fieldname.substring(1)).toString();
		return fieldname;

	}	   
	   
 `示例`
	  public static void main(String[] args) throws Exception {
		  ObjectFieldValidUtil onFieldValidUtil = new ObjectFieldValidUtil();
	 	 Information pInformation = new Information();
	 	  pInformation.setIdcardNo("131321321321313213213131h"); 
	      String filedName = "idcardNo"; 
	      HashMap<String,String> hashMap = ObjectFieldValidUtil.validField(filedName, pInformation); 
	      if (null != hashMap) {
	  					System.out.println(hashMap.get("comment")+"-------------"+hashMap.get("oldValue"));
	  	 } 
	 }
	 ```
	 须知
	 Information  类  必须 字段 必须要有 @Column(comment="xxx")格式, 否则无法获取到注解内容,可以自行扩展
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值