利用反射获取已经记载的dll的名字和利用反射释放已经加载的dll文件

获取已经加载的dll文件的名字

    try{
        ClassLoader classLoader = this.getClass().getClassLoader();
        Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
        field.setAccessible(true);
        Vector libs = (Vector) field.get(classLoader);
        logger.info("nativeLibraries size = " + libs.size());
        Iterator it = libs.iterator();
        Object o;
        while (it.hasNext()) {
            o = it.next();
            Field fieldName = o.getClass().getDeclaredField("name");
            fieldName.setAccessible(true);
            //这句是中的参数o是关键
            logger.info("nativeLibraries name = " + fieldName.get(o));
        }
    }catch (Exception e){
        logger.info("nativeLibraries = " + e.toString());
    }

释放dll文件,可以根据名称,释放特定的dll文件。

    try {
        ClassLoader classLoader = this.getClass().getClassLoader();
        Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
        field.setAccessible(true);
        Vector libs = (Vector) field.get(classLoader);
        Iterator it = libs.iterator();
        Object o;
        while (it.hasNext()) {
            o = it.next();
            Method finalize = o.getClass().getDeclaredMethod("finalize", new Class[0]);
            finalize.setAccessible(true);
            finalize.invoke(o, new Object[0]);
        }
    } catch (Exception ex) {
        System.out.println("卸载dll文件出错,需要重启服务器!");
        throw new RuntimeException(ex);
    }

你可能感兴趣的:(反射)