Dưới đây là một bộ sưu tập các reusable Java code snippets — dễ dùng, dễ bảo trì, và có thể tái sử dụng trong nhiều ứng dụng Java (đặc biệt hữu ích cho Spring Boot, microservices, hoặc utilities):
1. Centralized Validator
public class Validator {
public static void requireNonNull(Object value, String fieldName) {
if (value == null) {
throw new IllegalArgumentException(fieldName + " must not be null.");
}
}
public static void requireNonEmpty(String value, String fieldName) {
if (value == null || value.trim().isEmpty()) {
throw new IllegalArgumentException(fieldName + " must not be empty.");
}
}
}
2. Enum Parser (Safe)
public class EnumUtils {
public static <T extends Enum<T>> Optional<T> parseEnum(Class<T> enumType, String name) {
try {
return Optional.of(Enum.valueOf(enumType, name.toUpperCase()));
} catch (Exception e) {
return Optional.empty();
}
}
}
3. Date Formatter
public class DateUtil {
public static String format(LocalDateTime dateTime, String pattern) {
return dateTime.format(DateTimeFormatter.ofPattern(pattern));
}
public static LocalDateTime parse(String dateStr, String pattern) {
return LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
}
}
4. HTTP Client (GET wrapper with RestTemplate)
public class HttpClient {
private static final RestTemplate restTemplate = new RestTemplate();
public static <T> T get(String url, Class<T> responseType) {
return restTemplate.getForObject(url, responseType);
}
private static final HttpClient client = HttpClient.newHttpClient();
public static String get(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
5. JSON Mapper (using Jackson)
public class JsonUtil {
private static final ObjectMapper mapper = new ObjectMapper();
public static String toJson(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException("Failed to convert to JSON", e);
}
}
public static <T> T fromJson(String json, Class<T> clazz) {
try {
return mapper.readValue(json, clazz);
} catch (IOException e) {
throw new RuntimeException("Failed to parse JSON", e);
}
}
}
6. Result Wrapper
public class Result<T> {
private boolean success;
private String message;
private T data;
public static <T> Result<T> ok(T data) {
Result<T> result = new Result<>();
result.success = true;
result.data = data;
return result;
}
public static <T> Result<T> fail(String message) {
Result<T> result = new Result<>();
result.success = false;
result.message = message;
return result;
}
}
7. Password Hasher (BCrypt)
public class PasswordUtil {
private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
public static String hash(String password) {
return encoder.encode(password);
}
public static boolean matches(String rawPassword, String hashedPassword) {
return encoder.matches(rawPassword, hashedPassword);
}
}
8. Safe String Utils
public class StringUtils {
public static boolean isBlank(String str) {
return str == null || str.trim().isEmpty();
}
public static String safe(String str) {
return str != null ? str : "";
}
}
9. List-to-Map Converter
public class CollectionUtil {
public static <K, V> Map<K, V> toMap(List<V> list, Function<V, K> keyMapper) {
return list.stream().collect(Collectors.toMap(keyMapper, Function.identity()));
}
}
10. Thread Sleep Utility
public class SleepUtil {
public static void sleepSilently(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // best practice
}
}
}
11. List Cleaner
public class ListCleaner {
public static List<String> clean(List<String> input) {
return input.stream()
.filter(Objects::nonNull)
.map(String::trim)
.filter(s -> !s.isEmpty())
.distinct()
.toList();
}
}
12. File Reader
public class FileUtil {
public static String readAsString(String path) throws IOException {
return Files.readString(Paths.get(path));
}
}
13. Timer / Execution Logger
public class Timer {
public static void measure(String label, Runnable task) {
long start = System.currentTimeMillis();
task.run();
long duration = System.currentTimeMillis() - start;
System.out.println(label + " took " + duration + "ms");
}
}
14. Email Validator
public class EmailValidator {
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$");
public static boolean isValid(String email) {
return email != null && EMAIL_PATTERN.matcher(email).matches();
}
}
15. Simple In-Memory Cache
public class SimpleCache<K, V> {
private final ConcurrentHashMap<K, V> cache = new ConcurrentHashMap<>();
public V getOrCompute(K key, Function<K, V> loader) {
return cache.computeIfAbsent(key, loader);
}
}
Be First to Comment