Java 判断实体对象及所有属性是否为空的操作

网友投稿 310 2023-02-14

Java 判断实体对象及所有属性是否为空的操作

1、判断实体对象是否为空

2、判断对象所有属性是否为空

3、特别注意,实体类中如果有基本数据类型,会影响判断

package com.liuxd.object;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**

* Created by Liuxd on 2018/11/2.

*/

public class TestEntity {

public static void main(String[] args) {

User user1 = new User("Jack", "male", 17);

User user2 = new User();

boolean u1Flag = checkObjAllFieldsIsNull(user1);

boolean u2Flag = checkObjAllFieldsIsNull(user2);

System.out.println("user1 是否为空:" + u1Flag);

System.out.println("user2 是否为空:" + u2Flag);

}

/**

* 判断对象中属性值是否全为空

*

* @param object

* @return

*/

public static boolean checkObjAllFieldsIsNull(Object object) {

if (null == object) {

return true;

}

try {

for (Field f : object.getClass().getDeclaredFields()) {

f.setAccessible(true);

System.out.print(f.getName() + ":");

System.out.println(f.get(object));

if http://(f.get(object) != null && StringUtils.isNotBlank(f.get(object).toString())) {

return false;

}

}

} catch (Exception e) {

e.printStackTrace();

}

return true;

}

}

实体类:

package com.liuxd.object;

/**

* Created by Liuxd on 2018/11/2.

*/

public class User {

private String name;

private String gender;

/**

* 如果属性类型为基本数据类型,则会有默认值

* 影响正确判断,请特别注意

*/

// private int age;

private Integer age;

public User() {

}

public User(String name, String gender, int age) {

this.name = name;

this.gender = gender;

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

输出结果:

name:Jack

name:null

gender:null

age:null

user1 是否为空:false

user2 是否为空:true

补充知识:java 读取mongo数据库数据并直接下载,省略中间文件

插入测试数据:

package com.haiyoung.biz;

import org.bson.Document;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

/**

* Created by Haiyoung on 2018/4/1.

*/

@Service

public class MongoTest {

@Autowired

private MongoTemplate mongoTemplate;

/**

* 添加测试数据

*/

public void addData(){

List list = new ArrayList<>();

int count = 0;

for(int i=0;i<10000;i++){

Document doc = new Document();

doc.append("key","key"+i);

list.add(doc);

count++;

if(count % 300 == 0){//每 300 调条插入一次数据

mongoTemplate.insert(list, "qjGbuzcollection_test");

list.clear();

}

}

if(!list.isEmpty()){

mongoTemplate.insert(list, "collection_test");

}

}

}

import com.haiyoung.biz.MongoTest;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)

@SpringBootTest

public class DatabaseDownloadApplicationTests {

@Autowired

private MongoTest mongoTest;

@Test

public void insertData(){

mongoTest.addData();

}

}

下载服务类:

package com.haiyoung.biz.db_download;

import com.google.gson.Gson;

import com.mongodb.DBObject;

import com.mongodb.MongoException;

import org.bson.Document;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.dao.DataAccessException;

import org.springframework.data.mongodb.core.DocumentCallbackHandler;

import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.query.Query;

import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

@Service

public class MongoDownloadService {

@Autowired

private MongoTemplate mongoTemplate;

public interface MongoCollectionPrinter{

void print(List returnList);

void close();

}

/**

* 导出并下载数据的方法

*

* @param collectionName 要导出数据的集合名称

* @param batchNum 批量写入

* @param printer 实现下载

*/

public void export(String collectionName, int batchNum, MongoCollectionPrinter printer){

List returnList = new ArrayList<>();

Query query = new Query();

mongoTemplate.executeQuery(query, collectionName, new DocumentCallbackHandler() {

@Override

public void processDocument(Document document) throws MongoException, DataAccessException {

returnList.add(document);

if(returnList.size() % batchNum == 0){

printer.print(returnList);

returnList.clear();

}

}

});

if(!returnList.isEmpty()){

printer.print(returnList);

returnList.clear();

}

}

}

服务实现及web映射

package com.haiyoung.biz.db_download;

import com.google.gson.Gson;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.io.OutputStream;

import java.net.URLEncoder;

import java.util.List;

@Controller

@RequestMapping(value = "/page")

public class MongoDownloadController {

@Autowired

private MongoDownloadService mongoDownloadService;

private static String[] IEBrowserSignals = {"MSIE", "Trident", "Edge"};

/**

* 判断浏览器类型

*

* @param request

* @return

*/

private static boolean isMSBrowser(HttpServletRequest request){

String userAgent = request.getHeader("User-Agent");

for(String signal : IEBrowserSignals){

if(userAgent.contains(signal)){

return true;

}

}

return false;

}

/**

* 实现 MongoCollectionPrinter 接口

* 重写 print 和 close 方法

*/

public static class DownloadPrinter implements MongoDownloadService.MongoCollectionPrinter {

private OutputStream output = null;

private DownloadPrinter(HttpServletResponse response, String fileName) {

response.reset();// 清除 response 中的状态码以及headers

response.setContentType("application/x-msdownload");//设置文件类型

response.setHeader("Content-Disposition",

"attachment; filename=\""+fileName+"\"");// 设置文件名

try {

output = response.getOutputStream();// 获取输出流

} catch (IOException e) {

throw new RuntimeException(e);

}

}

@Override

public void print(List returnList) {

try {

output.write(new Gson().tojson(returnList).getBytes("UTF-8"));

} catch (IOException e) {

throw new RuntimeException(e);

}

}

@Override

public void close() {

try {

output.flush();

output.close();

} catch (IOException e) {

throw new RuntimeException(e);

}finally {

if (output !=null){

try {

output.close();

} catch (IOException e) {

throw new RuntimeException(e);

}

}

}

}

}

@RequestMapping(value = "/download")

public void export(HttpServletRequest request, HttpServletResponse response,

@RequestParam(value = "collectionName") String collectionName){

try {

String fileName = collectionName+".txt";

if(isMSBrowser(request)){

fileName = URLEncoder.encode(fileName, "UTF-8");

}else{

fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");

}

DownloadPrinter printer = new DownloadPrinter(response, fileName);

mongoDownloadService.export(collectionName, 300, printer);

printer.close();

}catch (Exception e){

throw new RuntimeException(e);

}

}

}

源代码链接:https://github.com/Haiyoung/HyProject/tree/master/database-download

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:How to choose between Apollo email finder and AroundDeal email finder?
下一篇:平台api接口对接教程(提供api接口的平台)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~