【Java】常用方法合集

以 DemoVo 为实体

bash 复制代码
import lombok.Data;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;

@Data
@ExcelIgnoreUnannotated
public class ExportPromoteUnitResult {

    private String id;

    @ExcelProperty(value = "学号")
    private String stuNo;

    @ExcelProperty(value = "姓名")
    private String stuName;
}
  1. 将一个实体的属性名取出来,整合为一个 List<String\[\]>格式
bash 复制代码
    private static List<String[]> getData() {
    	// new一个实体DemoVo
        DemoVo demo = new DemoVo();
        List<String[]> propertyNames = getPropertyNames(demo);
        return propertyNames;
    }

    public static List<String[]> getPropertyNames(Object obj) {
        List<String[]> properties = new ArrayList<>();
        Class<?> clazz = obj.getClass(); // 获取对象的Class对象
        Field[] fields = clazz.getDeclaredFields(); // 获取所有字段
        for (Field field : fields) {
            if (field.isAccessible()) { // 如果字段可访问,则添加其名称到列表中(对于私有字段可能需要设置可访问)
                properties.add(new String[]{field.getName()}); // 将属性名添加到List<String[]>中,每个String[]包含一个属性名
            } else {
                field.setAccessible(true); // 对于私有字段,需要设置可访问才能获取其名称(注意:这可能会破坏封装性)
                properties.add(new String[]{field.getName()}); // 添加属性名到List<String[]>中
            }
        }
        return properties; // 返回包含所有属性名的List<String[]>
    }
  1. 将一个实体的属性名整合为 List< String > 格式
bash 复制代码
	// new一个实体DemoVo,取出属性名
	DemoVo demo = new DemoVo();
	List<String[]> propertyNames = getPropertyNames(demo.getClass());
	System.out.print("propertyNames的输出结果为:" + propertyNames); 
	// propertyNames的输出结果为:[id,stuNo,stuName]
    
	// 获取实体类的所有字段名
	public List<String> getPropertyNames(Class<?> clazz) {
		Field[] fields = clazz.getDeclaredFields(); // 获取所有字段
    	List<String> propertyNames = new ArrayList<>(); // 新建一个数组propertyNames
    	for (Field field : fields) {
        	propertyNames.add(field.getName()); // 将所有字段放于数组propertyNames中
    	}
    	return propertyNames;
	}
  1. 根据属性名/字段名获取对应的值
bash 复制代码
    List<Map<String, Object>> maps = combinFixedLists(stuClassId);
	System.out.print("maps的输出结果为:" + maps);
	// maps的输出结果为:[{id=1,stuNo="2024001",stuName="李四",stuSex="1"},{id=2,stuNo="2024002",stuName="张三",stuSex="1"}]
	
	private List<Map<String, Object>> combinFixedLists(Long stuClassId) throws IllegalAccessException, NoSuchFieldException {
    	// 先根据stuClassId查询数据,此处不过多写sql语句了
        List<StudentClassResult> listObjects = this.queryStuResult(stuClassId);
        System.out.print("假如得出的结果为:" + listObjects);
        // 假如得出的结果为:[{id:1,stuNo:"2024001",stuName:"李四",stuSex:"1"},{id:2,stuNo:"2024002",stuName:"张三",stuSex:"1"}]
        
        List<Map<String, Object>> combinedList = new ArrayList<>();
        for (StudentClassResult object : listObjects) {
            Map<String, Object> fieldMap = new HashMap<>();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                String name = field.getName();
                field.setAccessible(true);
                fieldMap.put(field.getName(), field.get(object));
            }

            combinedList.add(fieldMap);
        }
        return combinedList;
    }
  1. 去掉List< String >中指定元素
bash 复制代码
	removePropertyFromString(propertyNames, "id");

	// 去掉指定属性名
    private static void removePropertyFromString(List<String> fixList, String fixElement) {
        Iterator<String> iterator = fixList.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            if (next == fixElement) {
                iterator.remove();
            }
        }
    }
  1. 取出JSON中的某属性名对应的属性值
bash 复制代码
	System.out.print(stuData)
	// stuData={"stuData":{"stuId":57,"photoList":{"fileName":["照片.png"],"filePath":["/qcbucket/2024/10/22/01.照片.png"]},"stuClassId":"3","stuName":"张三"}}

	Object stuId = null;
	Object photoList = null;
    Object stuClassId = null;
    Object stuName = null;
	JSONObject jsonObject = JSONObject.parseObject(stuData.toString());
    stuId = jsonObject.getJSONObject("stuData").get("stuId ");
    // 57
    photoList = jsonObject.getJSONObject("stuData").get("photoList");
    // "fileName":["照片.png"],"filePath":["/qcbucket/2024/10/22/01.照片.png"]
    stuClassId = jsonObject.getJSONObject("stuData").get("stuClassId");
    // "3"
    stuName = jsonObject.getJSONObject("stuData").get("stuName");
    // "张三"
  1. 保留两位数

(1)setScale

bash 复制代码
String num = "123.4567";
BigDecimal val = new BigDecimal(num);
BigDecimal roundedVal = val.setScale(2, RoundingMode.HALF_UP);
System.out.println(roundedVal); // 输出: 123.46

(2)sql语句

  1. 原数组 String\[\] originalArray,在指定元素后添加n个空字符串 ""
bash 复制代码
    // 原数组
	originalArray = new String[]{"apple","banana"}
	// 查找指定字符串
	String[] target = {"apple"}
	// 在指定字符串后追加num个 空字符串
	int num = 2;
	
	String[] array = modifyArray(originalArray, target, num);
	System.out("array的结果为:" + array);
	// array的结果为:["apple","","","banana"]
	 
    private static String[] modifyArray(String[] originalArray, String[] target, int n) {
        List<String> resultList = new ArrayList<>();
        for (String element : originalArray) {
            resultList.add(element);
            for (String add : target) {
                if (element.equals(add)) {
                    for (int i = 0; i < n; i++) {
                        resultList.add("");
                    }
                }
            }
        }
        return resultList.toArray(new String[0]);
    }
  1. 获取 resources 下 指定文件的路径
bash 复制代码
URL resource = getClass().getClassLoader().getResource("ip2region.xdb");
String XDB_PATH = resource.getPath();
相关推荐
Wang's Blog7 分钟前
Java 项目实战: 交友项目 - FastDFS:入门案例
java·开发语言·交友
apcipot_rain1 小时前
C++转Java日记(03)
java·开发语言·c++
皮皮林5511 小时前
Java实现微信扫码登录
java
Yyyyyy~3 小时前
【Java】Day4Web基础知识
java·spring boot
卷无止境4 小时前
RAGFlow 项目全景报告:从文档解析引擎到 Agent 原生数据库
后端·python
子兮曰4 小时前
Chrome 权限元素实战:144 与 151 的渐进增强写法
前端·javascript·chrome
灿飞屋5 小时前
Kotlin与Java虚拟机三:控制流
android·java·开发语言·后端·python·kotlin·安卓
benchmark_cc5 小时前
单只股票五档盘口接入个人研究仓库:QuantDash 读取、校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
NE_STOP5 小时前
Spring AI Alibaba - MCP入门
java
nice_lcj5205 小时前
【从零理解 Spring AI · 07】对话记忆:让模型记住上一句说了什么
java·spring ai·ai应用开发·chatmemory·对话记忆