本文共 5582 字,大约阅读时间需要 18 分钟。
在Java开发中,工具类是提高开发效率和代码质量的重要助力。本文将介绍几种常用的工具类及其应用场景。
在Java中,static变量属于类而非实例,且在类加载时初始化,整个生命周期内保持不变。因此,static变量无法动态读取或更新远端配置。
推荐的解决方案包括:
以下是一个实现示例:
public class ConfigManager { private static ConfigManager instance; private String remoteConfigValue; private ConfigManager() { fetchRemoteConfig(); startConfigRefreshTask(); } public static synchronized ConfigManager getInstance() { if (instance == null) { instance = new ConfigManager(); } return instance; } private void fetchRemoteConfig() { // 从远端配置中心获取配置值 // remoteConfigValue = ... } private void startConfigRefreshTask() { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(this::fetchRemoteConfig, 0, 1, TimeUnit.HOURS); } public String getRemoteConfigValue() { return remoteConfigValue; }} | 方法 | 目的 | 输出格式 | 注意事项 |
|---|---|---|---|
childPolicyOutputList.toString() | 获取对象字符串表示 | 格式类似JSON字符串,可能不符合标准 | 适用于简单展示,不需严格格式化 |
JSON.toJSON(childPolicyOutputList) | 将对象转换为JSON对象 | 返回JSON对象,不是字符串 | 适用于需要操作JSON对象时 |
JSON.toJSONString(childPolicyOutputList) | 将对象转换为JSON字符串 | 格式化的JSON字符串 | 适用于需要网络传输或存储时 |
// 示例1:使用toString()Object obj = new Object();System.out.println(obj.toString()); // 输出: java.lang.Object@15f3f6e// 示例2:使用JSON转换JSONObject json = new JSONObject();json.put("name", "Alice");String jsonString = json.toJSONString();System.out.println(jsonString); // 输出: {"name":"Alice"} // Apache Commons Langimport org.apache.commons.lang3.ObjectUtils;if (ObjectUtils.isEmpty(obj)) { // 处理为空情况}// Guavaimport com.google.common.base.Preconditions;Preconditions.checkNotNull(obj, "对象不能为空"); // Apache Commons Langimport org.apache.commons.lang3.StringUtils;System.out.println(StringUtils.isEmpty("")); // trueSystem.out.println(StringUtils.isBlank(" ")); // true import java.util.Collections;if (Collections.isNotEmpty(list)) { // 处理非空情况} // Apache Commons Collectionsimport org.apache.commons.collections4.MapUtils;if (MapUtils.isEmpty(map)) { // 处理为空情况} Optional类用于处理可能null的容器对象,提供了null安全的操作方法。
// 创建Optional实例Optional
import org.apache.commons.lang3.StringUtils;String str = "Hello World";System.out.println(StringUtils.reverse(str)); // "dlroW olleH"
import com.google.common.base.Strings;String str = "Guava";System.out.println(Strings.padEnd(str, 10, '!')); // "Guava!!!!!"
// Apache Commons Collectionsimport org.apache.commons.collections4.MapUtils;Mapmap = MapUtils.emptyMap();
// Apache Commons Collectionsimport org.apache.commons.collections4.ListUtils;Listlist = ListUtils.union(list1, list2);
// Google Guavaimport com.google.common.collect.Sets;Setset = Sets.newHashSet(list);
// 将Java对象转换为JSON字符串ObjectMapper mapper = new ObjectMapper();Person person = new Person("John", 30);String jsonString = mapper.writeValueAsString(person);// 将JSON字符串转换为Java对象Person deserializedPerson = mapper.readValue(jsonString, Person.class); // 将Java对象转换为JSON字符串Gson gson = new Gson();String jsonString = gson.toJson(person);// 将JSON字符串转换为Java对象Person deserializedPerson = gson.fromJson(jsonString, Person.class);
// 从集合创建流Listlist = Arrays.asList("apple", "banana", "orange");Stream streamFromList = list.stream();// 从数组创建流String[] array = {"apple", "banana", "orange"};Stream streamFromArray = Arrays.stream(array);
// 过滤Listnumbers = Arrays.asList(1, 2, 3, 4, 5);Stream filteredStream = numbers.stream().filter(x -> x > 2);// 映射Stream wordLengths = words.stream().map(String::length);// flattedListList flatList = numbers.stream().flatMap(Collection::stream);
// forEachwords.stream().forEach(System.out::println);// toArrayString[] wordArray = words.stream().toArray(String[]::new);// reduceOptionalsum = numbers.stream().reduce(Integer::sum);
public class Money { private BigDecimal amount; private CurrencyUnit unit; public Money(BigDecimal amount, CurrencyUnit unit) { this.amount = amount; this.unit = unit; } public BigDecimal getAmount() { return amount; } public CurrencyUnit getUnit() { return unit; } public Money add(Money other) { if (!getUnit().equals(other.getUnit())) { throw new IllegalArgumentException("单位不一致"); } return new Money(getAmount().add(other.getAmount()), getUnit()); }} Money money = new Money(new BigDecimal("1000.00"), EUR);money.add(new Money(new BigDecimal("500.00"), EUR); // 结果为1500.00 EUR public class AssertUtil { public static void isNotNull(Object input, String fieldName) { if (input == null) { throw new BusException("字段" + fieldName + "不能为空"); } } public static void equals(Object str1, Object str2, String err) { if (!str1.equals(str2)) { throw new BusException(err); } }} 转载地址:http://umhfk.baihongyu.com/