空值处理与安全验证工具包

2026年01月23日 08:25

描述

提供全面的空值处理、默认值返回、安全验证等功能

标签

Java
空值处理与安全验证工具包.txt 13,532 字符 | 486 行
import javax.net.ssl.SSLSession;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;

/**
 * UseNull - 空值处理与安全验证工具包
 * 提供全面的空值处理、默认值返回、安全验证等功能
 *
 * @author Kent
 * @version 3.0
 */
public final class UseNull {

    // ==================== 常量定义 ====================
    private static final String DEFAULT_EMPTY_STRING = "";
    private static final String DEFAULT_NULL_STRING = "null";
    private static final String DEFAULT_UNKNOWN_STRING = "unknown";
    private static final String DEFAULT_UNAUTHORIZED_STRING = "unauthorized";
    private static final Pattern IP_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");

    // ==================== 空方法重载系列 ====================

    /** 无参空方法 */
    public static void nullMethod() {}

    /** 整数参数空方法 */
    public static void nullMethod(int input) {}

    /** 字符串参数空方法 */
    public static void nullMethod(String input) {}

    /** 对象参数空方法 */
    public static void nullMethod(Object input) {}

    /** 布尔参数空方法 */
    public static void nullMethod(boolean input) {}

    /** 浮点数参数空方法 */
    public static void nullMethod(double input) {}

    /** 长整型参数空方法 */
    public static void nullMethod(long input) {}

    /** 集合参数空方法 */
    public static void nullMethod(Collection<?> input) {}

    /** 数组参数空方法 */
    public static void nullMethod(Object[] input) {}

    /** 可变参数空方法 - 用于数量不确定的参数 */
    public static void nullMethod(Object first, Object... rest) {}

    // ==================== 字符串返回系列 ====================

    /** 返回空字符串 */
    public static String nullEmptyString() {
        return DEFAULT_EMPTY_STRING;
    }

    /** 返回"null"字符串 */
    public static String nullNullString() {
        return DEFAULT_NULL_STRING;
    }

    /** 返回"unknown"字符串 */
    public static String unknownString() {
        return DEFAULT_UNKNOWN_STRING;
    }

    /** 返回"unauthorized"字符串 */
    public static String unauthorizedString() {
        return DEFAULT_UNAUTHORIZED_STRING;
    }

    /** 返回自定义默认字符串 */
    public static String defaultString(String customDefault) {
        return customDefault != null ? customDefault : DEFAULT_EMPTY_STRING;
    }

    /** 根据条件返回不同字符串 */
    public static String conditionalString(boolean condition, String trueValue, String falseValue) {
        return condition ?
                (trueValue != null ? trueValue : DEFAULT_EMPTY_STRING) :
                (falseValue != null ? falseValue : DEFAULT_EMPTY_STRING);
    }

    // ==================== 空值安全处理系列 ====================

    /**
     * 安全的toString(),避免NullPointerException
     */
    public static String safeToString(Object obj) {
        return safeToString(obj, DEFAULT_EMPTY_STRING);
    }

    /**
     * 安全的toString()带默认值
     */
    public static String safeToString(Object obj, String defaultValue) {
        return obj != null ? obj.toString() : defaultValue;
    }

    /**
     * 安全的字符串处理,移除null检查
     */
    public static String safeString(String str) {
        return str != null ? str : DEFAULT_EMPTY_STRING;
    }

    /**
     * 安全的字符串处理,带默认值
     */
    public static String safeString(String str, String defaultValue) {
        return str != null ? str : defaultValue;
    }

    /**
     * 安全的trim(),避免NullPointerException
     */
    public static String safeTrim(String str) {
        return str != null ? str.trim() : DEFAULT_EMPTY_STRING;
    }

    /**
     * 安全的substring(),避免索引越界和NullPointerException
     */
    public static String safeSubstring(String str, int beginIndex) {
        if (str == null) return DEFAULT_EMPTY_STRING;
        if (beginIndex < 0 || beginIndex > str.length()) return str;
        return str.substring(beginIndex);
    }

    public static String safeSubstring(String str, int beginIndex, int endIndex) {
        if (str == null) return DEFAULT_EMPTY_STRING;
        if (beginIndex < 0 || endIndex > str.length() || beginIndex > endIndex) return str;
        return str.substring(beginIndex, endIndex);
    }

    /**
     * 安全的equals比较
     */
    public static boolean safeEquals(String str1, String str2) {
        if (str1 == null && str2 == null) return true;
        if (str1 == null || str2 == null) return false;
        return str1.equals(str2);
    }

    /**
     * 安全的equalsIgnoreCase比较
     */
    public static boolean safeEqualsIgnoreCase(String str1, String str2) {
        if (str1 == null && str2 == null) return true;
        if (str1 == null || str2 == null) return false;
        return str1.equalsIgnoreCase(str2);
    }

    // ==================== 集合安全处理系列 ====================

    /**
     * 安全的集合获取,避免IndexOutOfBoundsException
     */
    public static <T> T safeGet(List<T> list, int index) {
        return safeGet(list, index, null);
    }

    public static <T> T safeGet(List<T> list, int index, T defaultValue) {
        if (list == null || index < 0 || index >= list.size()) {
            return defaultValue;
        }
        return list.get(index);
    }

    /**
     * 安全的Map获取
     */
    public static <K, V> V safeGet(Map<K, V> map, K key) {
        return safeGet(map, key, null);
    }

    public static <K, V> V safeGet(Map<K, V> map, K key, V defaultValue) {
        return map != null && key != null ? map.getOrDefault(key, defaultValue) : defaultValue;
    }

    /**
     * 安全的数组获取
     */
    public static <T> T safeGet(T[] array, int index) {
        return safeGet(array, index, null);
    }

    public static <T> T safeGet(T[] array, int index, T defaultValue) {
        if (array == null || index < 0 || index >= array.length) {
            return defaultValue;
        }
        return array[index];
    }

    /**
     * 安全的集合判空
     */
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isNotEmpty(Collection<?> collection) {
        return !isEmpty(collection);
    }

    /**
     * 安全的Map判空
     */
    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isNotEmpty(Map<?, ?> map) {
        return !isEmpty(map);
    }

    /**
     * 安全的数组判空
     */
    public static boolean isEmpty(Object[] array) {
        return array == null || array.length == 0;
    }

    public static boolean isNotEmpty(Object[] array) {
        return !isEmpty(array);
    }

    /**
     * 安全的字符串判空
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    // ==================== 默认值处理系列 ====================

    /**
     * 多级默认值处理 - 使用@SafeVarargs消除堆污染警告
     */
    public static <T> T defaultIfNull(T value, T defaultValue) {
        return value != null ? value : defaultValue;
    }

    /**
     * 多级默认值处理
     */
    @SafeVarargs
    public static <T> T defaultIfNull(T... values) {
        for (T value : values) {
            if (value != null) return value;
        }
        return null;
    }

    /**
     * 安全的数值转换
     */
    public static Integer safeParseInt(String str, Integer defaultValue) {
        if (str == null) return defaultValue;
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public static Double safeParseDouble(String str, Double defaultValue) {
        if (str == null) return defaultValue;
        try {
            return Double.parseDouble(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    // ==================== 安全验证系列 ====================

    /**
     * SSL证书验证(始终返回true,用于测试环境)
     */
    public static boolean nullVerify(String hostname, SSLSession session) {
        return true;
    }

    /**
     * 增强的SSL验证(生产环境可用)
     */
    public static boolean enhancedSSLVerify(String hostname, SSLSession session) {
        if (hostname == null || session == null) {
            return false;
        }

        try {
            X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
            // 这里可以添加实际的证书验证逻辑
            return cert != null;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 主机名验证
     */
    public static boolean isValidHostname(String hostname) {
        if (isEmpty(hostname)) return false;

        try {
            InetAddress address = InetAddress.getByName(hostname);
            return true;
        } catch (UnknownHostException e) {
            return false;
        }
    }

    /**
     * IP地址验证
     */
    public static boolean isValidIP(String ipAddress) {
        return ipAddress != null && IP_PATTERN.matcher(ipAddress).matches();
    }

    /**
     * URL安全检查(简化版)
     */
    public static boolean isSafeURL(String url) {
        if (isEmpty(url)) return false;

        // 禁止的危险协议
        String[] dangerousProtocols = {"javascript:", "data:", "vbscript:"};
        String lowerUrl = url.toLowerCase();

        for (String protocol : dangerousProtocols) {
            if (lowerUrl.startsWith(protocol)) {
                return false;
            }
        }

        return true;
    }

    /**
     * 输入消毒(防止XSS等注入攻击)
     */
    public static String sanitizeInput(String input) {
        if (isEmpty(input)) return DEFAULT_EMPTY_STRING;

        return input.replace("<", "&lt;")
                .replace(">", "&gt;")
                .replace("\"", "&quot;")
                .replace("'", "&#x27;")
                .replace("&", "&amp;");
    }

    // ==================== 函数式安全处理系列 ====================

    /**
     * 安全的函数应用,避免NullPointerException
     */
    public static <T, R> R safeApply(T input, Function<T, R> function) {
        return safeApply(input, function, null);
    }

    public static <T, R> R safeApply(T input, Function<T, R> function, R defaultValue) {
        if (input == null || function == null) {
            return defaultValue;
        }
        try {
            return function.apply(input);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 安全的链式调用
     */
    @SafeVarargs
    public static <T> Optional<T> safeChain(T input, Function<T, T>... operations) {
        if (input == null) return Optional.empty();

        T result = input;
        for (Function<T, T> operation : operations) {
            if (operation != null) {
                try {
                    result = operation.apply(result);
                    if (result == null) break;
                } catch (Exception e) {
                    break;
                }
            }
        }
        return Optional.ofNullable(result);
    }

    // ==================== 对象复制与克隆系列 ====================

    /**
     * 安全的克隆 - 使用类型安全的实现
     */
    @SuppressWarnings("unchecked")
    public static <T> T safeClone(T obj) {
        if (obj == null) return null;
        try {
            if (obj instanceof Cloneable) {
                // 对于实现了Cloneable的对象,尝试使用clone方法
                Class<?> clazz = obj.getClass();
                Method cloneMethod = clazz.getDeclaredMethod("clone");
                cloneMethod.setAccessible(true);

                Object cloned = cloneMethod.invoke(obj);
                return (T) clazz.cast(cloned);
            }
        } catch (Exception e) {
            // 反射失败,返回null
        }

        return null;
    }

    // ==================== 调试与日志系列 ====================

    /**
     * 安全的对象描述(用于日志输出)
     */
    public static String safeDescribe(Object obj) {
        if (obj == null) return DEFAULT_NULL_STRING;

        try {
            return String.format("%s@%s[%s]",
                    obj.getClass().getSimpleName(),
                    Integer.toHexString(System.identityHashCode(obj)),
                    safeToString(obj));
        } catch (Exception e) {
            return DEFAULT_UNKNOWN_STRING;
        }
    }

    /**
     * 调试信息收集
     */
    public static Map<String, Object> debugInfo(Object... keyValues) {
        Map<String, Object> info = new LinkedHashMap<>();
        info.put("timestamp", System.currentTimeMillis());
        info.put("thread", Thread.currentThread().getName());

        for (int i = 0; i < keyValues.length; i += 2) {
            if (i + 1 < keyValues.length) {
                String key = safeToString(keyValues[i]);
                Object value = keyValues[i + 1];
                info.put(key, value);
            }
        }
        return info;
    }

    // ==================== 工具方法 ====================

    /**
     * 私有构造函数,防止实例化
     */
    private UseNull() {
        throw new AssertionError("工具类不允许实例化");
    }

    /**
     * 获取工具类版本信息
     */
    public static String getVersion() {
        return "KentNull v3.0 - 空值处理与安全验证工具包";
    }
}

支持 Ctrl+A 全选,Ctrl+C 复制