Java反射机制判断Object对象的所有属性值是否为空。

原文链接: https://blog.csdn.net/zhouzhiwengang/article/details/89028758

本文仅作为一个用法示例, 不实现任何具体功能, 在本次测试中将所有空值或者空字符的属性名打印。

package test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import entity.F100018DTO;

/**
 * <p>
 * Title: F100018Utils
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author JX1811
 * @date 2019年8月21日
 */
public class F100018Utils {

	/**
	 * <p>Title: validateFild</p> 
	 * <p>Description: 这是一个以反射机制为基础的判断对象内部的属性是否为空的方法</p>
	 * @param obj      要判断的对象实例
	 * @param exclFild 放行的属性, 不需要做判断的属性
	 * @return 布尔类型, 这个可以根据需求做出变更
	 */  
	public static boolean validateFild(Object obj, List<String> exclFild) {

		boolean target = false;

		for (Field f : obj.getClass().getDeclaredFields()) {
			f.setAccessible(true);
			try {
				String name = f.getName();
				// 判断属性名称是否在排除属性值中
				if (!exclFild.contains(name)) {
					if (f.get(obj) == null || f.get(obj).equals("")) {
						// 判断字段是否为空,并且对象属性中的基本都会转为对象类型来判断
						target = true;
						System.out.println(name);
					}
				}
			} catch (IllegalArgumentException e) {
				target = false;
				System.out.println("对象属性解析异常" + e.getMessage());
				return target;
			} catch (IllegalAccessException e) {
				target = false;
				System.out.println("对象属性解析异常" + e.getMessage());
				return target;
			}
		}
		return target;
	} 
	
	/**
	 * <p>Title: main</p> 
	 * <p>Description:调用的案例 </p>
	 * @param args
	 */  
	public static void main(String[] args) {
		F100018DTO f100018dto = new F100018DTO(null, "", null, null);
		List<String> exclFild = new ArrayList<String>();
		exclFild.add("age");
		System.out.println(F100018Utils.validateFild(f100018dto, exclFild));
	}

}

//测试用的类

package entity;


/** 
* <p>Title: F100018DTO</p>  
* <p>Description: 测试使用的实体类</p>  
* @author JX1811
* @date 2019年8月21日  
*/  
public class F100018DTO {

	private String name;
	private String password;
	private Integer age;
	private String graduate;	
	
	public F100018DTO() {}

	public F100018DTO(String name, String password, Integer age, String graduate) {
		this.name = name;
		this.password = password;
		this.age = age;
		this.graduate = graduate;
	}	
	
	public String getName() {return name;}
	public void setName(String name) {this.name = name;}
	public String getPassword() {return password;}
	public void setPassword(String password) {this.password = password;}
	public int getAge() {	return age;}
	public void setAge(Integer age) {this.age = age;}
	public String getGraduate() {return graduate;}
	public void setGraduate(String graduate) {this.graduate = graduate;} 
	
}

新手上路, 请多多指教。

发布了22 篇原创文章 · 获赞 3 · 访问量 3442

猜你喜欢

转载自blog.csdn.net/ChyoD1811/article/details/99975344
今日推荐