ClassNotfoundException:java.net.InetAddress$CacheEntry

发布时间 2023-09-22 17:19:50作者: 做个读书人

一个需求,需要修改本地的dns解析,去验证业务的正确性,修改本地的hosts文件需要频繁的修改本地磁盘文件。

使用工具包(https://github.com/tanhaichao/javahost)这个工具类实际是通过反射机制,去修改了InetAddress中的cache值,来实现dns解析的修改。

CloseableHttpClient方法在做connect的时候,利用下述方法先获取DNS数据。InetAddress.getAllByName获取到相应的DNS解析记录,然后根据dns解析去建立socket链接。

定位到出错问题发生在:

protected Object createCacheEntry(String host, String[] ips) {
        try {
            long expiration = System.currentTimeMillis() + 315360000000L;
            InetAddress[] addresses = new InetAddress[ips.length];
 
            for(int i = 0; i < addresses.length; ++i) {
                addresses[i] = InetAddress.getByAddress(host, InetAddress.getByName(ips[i]).getAddress());
            }
 
            String className = "java.net.InetAddress$CacheEntry";
            Class<?> clazz = Class.forName(className);
            Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
            constructor.setAccessible(true);
            return constructor.newInstance(addresses, expiration);
        } catch (Exception var9) {
            throw new RuntimeException(var9.getMessage(), var9);
        }
    }

没有找到java.net.InetAddress$CacheEntry 这个内部类,排查过程中发现JDK(1.8_372)中没有包含此内部类,更换jdk版本(1.8_381)启动正常。