首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]揭秘Java编程必备:30个实用工具类,轻松提升开发效率

发布于 2025-06-20 15:34:30
0
9

在Java编程的世界里,工具类是开发者提升工作效率的得力助手。这些工具类涵盖了字符串处理、时间日期、文件操作、数据库连接等多个方面,下面将详细介绍30个实用工具类,帮助开发者轻松提升开发效率。1. S...

在Java编程的世界里,工具类是开发者提升工作效率的得力助手。这些工具类涵盖了字符串处理、时间日期、文件操作、数据库连接等多个方面,下面将详细介绍30个实用工具类,帮助开发者轻松提升开发效率。

1. StringUtil.java

字符串处理工具类,提供字符串拼接、分割、格式化、去除空格、检查是否为空等方法,简化字符串操作。

public class StringUtil { public static String join(String separator, String... elements) { return String.join(separator, elements); } public static String trim(String str) { return str == null ? null : str.trim(); } public static boolean isEmpty(String str) { return str == null || str.isEmpty(); }
}

2. TimeUtil.java 和 DateUtil.java

时间日期工具类,提供获取当前时间、时间格式化、时间比较、日期加减等功能。

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeUtil { public static String getCurrentTime() { return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); }
}
public class DateUtil { public static String addDays(String dateStr, int days) { LocalDateTime date = LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd")); return date.plusDays(days).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); }
}

3. Time.java

自定义时间工具类,补充Java内置java.time包中的功能,或提供特定场景下的优化方法。

import java.time.ZonedDateTime;
public class Time { public static ZonedDateTime getUTCNow() { return ZonedDateTime.now(); }
}

4. simpleServer.java 和 simpleClient.java

通信服务端和客户端工具类,封装Socket编程细节,方便搭建和使用服务器和客户端。

import java.io.*;
import java.net.*;
public class simpleServer { public static void startServer(int port) { try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server started on port " + port); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { out.println("Server received: " + inputLine); } } catch (IOException e) { e.printStackTrace(); } }
}
public class simpleClient { public static void startClient(String host, int port) { try (Socket socket = new Socket(host, port)) { PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println("Hello from client!"); String response = in.readLine(); System.out.println("Server response: " + response); } catch (IOException e) { e.printStackTrace(); } }
}

5. FileUtil.java

文件操作工具类,提供读取、写入、创建、删除、复制、移动文件和目录等方法。

import java.io.*;
import java.nio.file.*;
public class FileUtil { public static void copyFile(String sourcePath, String destPath) throws IOException { Files.copy(Paths.get(sourcePath), Paths.get(destPath)); } public static void deleteFile(String path) throws IOException { Files.delete(Paths.get(path)); }
}

6. ConnectDB.java

数据库连接工具类,负责数据库连接、查询、增删改查等操作,简化数据库操作。

import java.sql.*;
public class ConnectDB { public static Connection getConnection() throws SQLException { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "username"; String password = "password"; return DriverManager.getConnection(url, user, password); } public static void query(String sql) throws SQLException { try (Connection conn = getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { System.out.println(rs.getString(1)); } } }
}

7. ReflectionUtil.java

反射工具类,提供通过反射获取类信息、创建对象、调用方法等功能。

import java.lang.reflect.*;
public class ReflectionUtil { public static Object createInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = Class.forName(className); return clazz.newInstance(); } public static Method getMethod(String className, String methodName, Class... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { Class clazz = Class.forName(className); return clazz.getMethod(methodName, parameterTypes); }
}

8. ReflectionFieldUtil.java

反射字段工具类,提供通过反射获取字段值、设置字段值等功能。

import java.lang.reflect.*;
public class ReflectionFieldUtil { public static Object getFieldValue(Object obj, String fieldName) throws NoSuchFieldException, IllegalAccessException { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); return field.get(obj); } public static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, value); }
}

9. ThreadUtil.java

线程工具类,提供创建线程、线程池、同步锁等功能。

import java.util.concurrent.*;
public class ThreadUtil { public static Thread createThread(Runnable runnable) { return new Thread(runnable); } public static ExecutorService createThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, new LinkedBlockingQueue<>()); } public static void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
}

10. CollectionsUtil.java

集合工具类,提供集合转换、操作、排序等功能。

import java.util.*;
public class CollectionsUtil { public static  List toList(T[] array) { return Arrays.asList(array); } public static  Set toSet(T[] array) { return new HashSet<>(Arrays.asList(array)); } public static  List sort(List list, Comparator comparator) { list.sort(comparator); return list; }
}

11. SerializationUtil.java

序列化工具类,提供对象序列化和反序列化功能。

import java.io.*;
public class SerializationUtil { public static void serialize(Object obj, String filePath) throws IOException { try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) { oos.writeObject(obj); } } public static  T deserialize(String filePath, Class clazz) throws IOException, ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) { return clazz.cast(ois.readObject()); } }
}

12. MathUtil.java

数学工具类,提供常用数学计算功能。

public class MathUtil { public static double round(double value, int scale) { return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale); } public static double min(double... values) { double min = Double.MAX_VALUE; for (double value : values) { min = Math.min(min, value); } return min; } public static double max(double... values) { double max = Double.MIN_VALUE; for (double value : values) { max = Math.max(max, value); } return max; }
}

13. EnumUtil.java

枚举工具类,提供枚举转换、操作等功能。

import java.util.*;
public class EnumUtil { public static > E fromString(Class enumClass, String enumName) { return Arrays.stream(enumClass.getEnumConstants()).filter(e -> e.name().equals(enumName)).findFirst().orElse(null); } public static > List toStringList(Class enumClass) { return Arrays.stream(enumClass.getEnumConstants()).map(Enum::name).collect(Collectors.toList()); }
}

14. JSONUtil.java

JSON工具类,提供JSON对象解析、转换等功能。

import com.fasterxml.jackson.databind.ObjectMapper;
public class JSONUtil { private static final ObjectMapper objectMapper = new ObjectMapper(); public static String toJson(Object obj) throws IOException { return objectMapper.writeValueAsString(obj); } public static  T fromJson(String json, Class clazz) throws IOException { return objectMapper.readValue(json, clazz); }
}

15. XMLUtil.java

XML工具类,提供XML对象解析、转换等功能。

import org.w3c.dom.*;
import javax.xml.parsers.*;
public class XMLUtil { public static Document parseXML(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(xml))); } public static String toXML(Document document) throws Exception { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource domSource = new DOMSource(document); StringWriter writer = new StringWriter(); StreamResult streamResult = new StreamResult(writer); transformer.transform(domSource, streamResult); return writer.getBuffer().toString().replaceAll("\n|\r", ""); }
}

16. RegexUtil.java

正则表达式工具类,提供正则表达式匹配、替换等功能。

public class RegexUtil { public static boolean matches(String input, String regex) { return input.matches(regex); } public static String replace(String input, String regex, String replacement) { return input.replaceAll(regex, replacement); }
}

17. URLUtil.java

URL工具类,提供URL解析、操作等功能。

import java.net.*;
public class URLUtil { public static String getDomain(String url) throws MalformedURLException { URL urlObj = new URL(url); return urlObj.getHost(); } public static String getPath(String url) throws MalformedURLException { URL urlObj = new URL(url); return urlObj.getPath(); }
}

18. EmailUtil.java

电子邮件工具类,提供电子邮件发送、解析等功能。

import javax.mail.*;
import javax.mail.internet.*;
public class EmailUtil { public static void sendEmail(String to, String subject, String content) throws MessagingException { Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.example.com"); properties.put("mail.smtp.port", "587"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password"); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from@example.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(subject); message.setText(content); Transport.send(message); }
}

19. HTTPUtil.java

HTTP工具类,提供HTTP请求、响应处理等功能。

import java.io.*;
import java.net.*;
import java.util.zip.GZIPInputStream;
public class HTTPUtil { public static String get(String url) throws IOException { URL urlObj = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod("GET"); try (InputStream inputStream = connection.getInputStream()) { if ("gzip".equals(connection.getContentEncoding())) { inputStream = new GZIPInputStream(inputStream); } return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); } }
}

20. CacheUtil.java

缓存工具类,提供缓存数据存储、读取等功能。

import java.util.*;
public class CacheUtil { private static final Map cache = new HashMap<>(); public static void put(String key, Object value) { cache.put(key, value); } public static Object get(String key) { return cache.get(key); } public static void remove(String key) { cache.remove(key); }
}

21. LogUtil.java

日志工具类,提供日志记录、级别设置等功能。

import java.util.logging.*;
public class LogUtil { private static final Logger logger = Logger.getLogger(LogUtil.class.getName()); public static void info(String message) { logger.info(message); } public static void warning(String message) { logger.warning(message); } public static void severe(String message) { logger.severe(message); }
}

22. ReflectionMethodUtil.java

反射方法工具类,提供通过反射调用方法、获取方法信息等功能。

import java.lang.reflect.*;
public class ReflectionMethodUtil { public static Object invokeMethod(Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method method = obj.getClass().getMethod(methodName, getParameterTypes(args)); return method.invoke(obj, args); } private static Class[] getParameterTypes(Object[] args) { return Arrays.stream(args).map(Object::getClass).toArray(Class[]::new); }
}

23. ReflectionConstructorUtil.java

反射构造方法工具类,提供通过反射创建对象、获取构造方法信息等功能。

import java.lang.reflect.*;
public class ReflectionConstructorUtil { public static Object createInstance(Class clazz, Object... args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Constructor constructor = clazz.getConstructor(getParameterTypes(args)); return constructor.newInstance(args); } private static Class[] getParameterTypes(Object[] args) { return Arrays.stream(args).map(Object::getClass).toArray(Class[]::new); }
}

24. ReflectionAnnotationUtil.java

反射注解工具类,提供通过反射获取注解信息、注解值等功能。

import java.lang.annotation.*;
import java.lang.reflect.*;
public class ReflectionAnnotationUtil { public static  T getAnnotation(Class clazz, Class annotationClass) { return clazz.getAnnotation(annotationClass); } public static  T getAnnotation(Member member, Class annotationClass) { return member.getAnnotation(annotationClass); }
}

25. ReflectionGenericUtil.java

反射泛型工具类,提供通过反射获取泛型信息、泛型类型等功能。

import java.lang.reflect.*;
public class ReflectionGenericUtil { public static Type getGenericSuperclass(Class clazz) { return clazz.getGenericSuperclass(); } public static Type[] getGenericInterfaces(Class clazz) { return clazz.getGenericInterfaces(); } public static Type getGenericReturnType(Method method) { return method.getGenericReturnType(); } public static Type[] getGenericParameterTypes(Method method) { return method.getGenericParameterTypes(); }
}

26. ReflectionParameterUtil.java

反射参数工具类,提供通过反射获取参数信息、参数值等功能。

import java.lang.reflect.*;
public class ReflectionParameterUtil { public static Parameter[] getParameters(Method method) { return method.getParameters(); } public static Object getParameter(Object obj, Method method, int index) throws IllegalAccessException { Parameter[] parameters = method.getParameters(); if (index >= 0 && index < parameters.length) { Parameter parameter = parameters[index]; return parameter.getType().cast(obj); } return null; }
}

27. ReflectionAnnotationValueUtil.java

反射注解值工具类,提供通过反射获取注解值信息、注解值等功能。

import java.lang.annotation.*;
import java.lang.reflect.*;
public class ReflectionAnnotationValueUtil { public static Object getAnnotationValue(Annotation annotation, String fieldName) throws NoSuchFieldException, IllegalAccessException { Class annotationType = annotation.getClass(); Field field = annotationType.getDeclaredField(fieldName); field.setAccessible(true); return field.get(annotation); }
}

28. ReflectionConstructorParameterUtil.java

反射构造方法参数工具类,提供通过反射获取构造方法参数信息、构造方法参数值等功能。

import java.lang.reflect.*;
public class ReflectionConstructorParameterUtil { public static Constructor[] getConstructors(Class clazz) { return clazz.getConstructors(); } public static Parameter[] getConstructorParameters(Constructor constructor) { return constructor.getParameters(); } public static Object getConstructorParameter(Constructor constructor, int index) throws IllegalAccessException { Parameter[] parameters = constructor.getParameters(); if (index >= 0 && index < parameters.length) { Parameter parameter = parameters[index]; return parameter.getType().cast(constructor.newInstance()); } return null; }
}

29. ReflectionFieldParameterUtil.java

反射字段参数工具类,提供通过反射获取字段信息、字段值等功能。

import java.lang.reflect.*;
public class ReflectionFieldParameterUtil { public static Field[] getFields(Class clazz) { return clazz.getFields(); } public static Object getField(Object obj, Field field) throws IllegalAccessException { field.setAccessible(true); return field.get(obj); }
}

30. ReflectionMethodParameterUtil.java

反射方法参数工具类,提供通过反射获取方法信息、方法值等功能。

import java.lang.reflect.*;
public class ReflectionMethodParameterUtil { public static Method[] getMethods(Class clazz) { return clazz.getMethods(); } public static Object getMethod(Object obj, Method method) throws IllegalAccessException, InvocationTargetException { return method.invoke(obj); }
}

以上是30个实用工具类的详细介绍,这些工具类可以帮助开发者简化编程工作,提高开发效率。在实际开发中,可以根据需要选择合适的工具类,使代码更加简洁、易读、易维护。

评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告
站长交流