如何在Java代码中测试Class.forName调用?

2022-09-04 23:38:35

我最近一直在用java来搞砸ClassLoaders,试图测试使用自定义的类的动态加载(使用)的代码。Class.forName(String name)ClassLoader

我有自己的自定义设置,它应该可以配置为在尝试加载给定类时抛出一个。ClassLoaderClassNotFoundException

public class CustomTestClassLoader extends ClassLoader {
    private static String[] notAllowed = new String[]{};
    public static void setNotAllowed(String... nonAllowedClassNames) {
        notAllowed = nonAllowedClassNames;
    }
    public static String[] getNotAllowed() {
        return notAllowed;
    }
    public CustomTestClassLoader(ClassLoader parent){super(parent);}
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        for (String s : notAllowed) {
            if (name.equals(s)) {
                throw new ClassNotFoundException("Loading this class is not allowed for testing purposes.");
            }
        }

        if(name.startsWith("java") || name.startsWith("sun") || getClass().getName().equals(name)) {
            return getParent().loadClass(name);
        }

        Class<?> gotOne = super.findLoadedClass(name);
        if (gotOne != null) {
            return gotOne;
        }

        Class<?> c;
        InputStream in = getParent().getResourceAsStream(name.replace('.', '/')+".class");
        if (in == null) {
            throw new ClassNotFoundException("Couldn't locate the classfile: "+name);
        }
        try {
            byte[] classData = readBytes(in);
            c = defineClass(name, classData, 0, classData.length);
        } catch(IOException e) {
            throw new ClassNotFoundException("Couldn't read the class data.", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {/* not much we can do at this point */}
        }

        if (resolve) {
            resolveClass(c);
        }
        return c;
    }

    private byte[] readBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[4194304];
        int read = in.read(buffer);
        while (read != -1) {
            out.write(buffer, 0, read);
            read = in.read(buffer);
        }
        out.close();
        return out.toByteArray();
    }
}

我用它来将其设置为默认值。我希望能够通过禁止使用某些类名来强制a。但是,它仅适用于 ,而不适用于 :-Djava.system.class.loader=com.classloadertest.test.CustomTestClassLoaderclassloaderClassLoaderClassNotFoundExceptionCustomTestClassLoader.setNotAllowed(String...)ClassLoader.loadClassClass.forName

public void test() {
    ClassLoader loader = this.getClass().getClassLoader();
    CustomTestClassLoader custom = (CustomTestClassLoader)loader; 
    CustomTestClassLoader.setNotAllowed(NAME);
    for (String s : custom.getNotAllowed())
        System.out.println("notAllowed: "+s);
    try {
        System.out.println(Class.forName(NAME));
    } catch (ClassNotFoundException e) {
        System.out.println("forName(String) failed");
    }
    try {
        System.out.println(Class.forName(NAME,false,custom));
    } catch (ClassNotFoundException e) {
        System.out.println("forName(String,boolean,ClassLoader) failed");
    }
    try {
        System.out.println(custom.loadClass(NAME));
    } catch (ClassNotFoundException e) {
        System.out.println("ClassLoader.loadClass failed");
    }
}

现在我预计所有三个尝试块都会失败,因为的文档说它使用调用方的调用方(在此测试中应该是自定义/加载程序)。但是,只有最终的尝试块会失败。这是我得到的输出:Class.forNameClassLoader

notAllowed: com.classloadertest.test.Test
class com.classloadertest.test.Test
class com.classloadertest.test.Test
ClassLoader.loadClass failed

是否真的使用了 ?如果是这样,有哪些方法?它似乎在使用本机调用,所以我不知道它在幕后做了什么。Class.forNameclassloader

当然,如果有人知道测试呼叫的任何替代方法,也将不胜感激。Class.forName()


答案 1

Class.forName()使用从中调用它的类的类装入器(例如,在你的例子中,包含该方法的类)。因此,如果您在其他环境中运行它,这将导致问题。test()

更新该类加载器将用于加载您的类。这可能是解决方案:它可能是一个 Eclipse 定义的类装入器,可以访问你的类,所以它会装入它。尽管它的父级(或根)类装入器具有禁止装入该类的显式规则。Class.forName()Test

我仍然建议为此实例化创建一个包装类。您应该使用 您的 加载该类,然后才能在该类中使用。CustomTestClassLoaderClass.forName()


答案 2

推荐