13

私は最近、Java で ClassLoaders をいじっていて、クラスの動的ロード ( を使用Class.forName(String name)) をカスタムClassLoader.

特定のクラスをロードしようとしたときにスローするように構成可能であるはずの、独自のカスタムClassLoader設定があります。ClassNotFoundException

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();
    }
}

-Djava.system.class.loader=com.classloadertest.test.CustomTestClassLoaderこれclassloaderをデフォルトとして設定するために使用していますClassLoaderClassNotFoundExceptionを使用して特定のクラス名を禁止することで、強制できることを望んでいましたCustomTestClassLoader.setNotAllowed(String...)。ただし、それは に対してのみ機能しClassLoader.loadClass、 に対しては機能しませんClass.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");
    }
}

のドキュメントには、呼び出し元 (このテストでは custom/loader である必要があります) をClass.forName使用していると書かれているため、3 つの try ブロックはすべて失敗すると予想していました。ClassLoaderただし、最後の try ブロックのみが失敗します。これが私が得る出力です:

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

Class.forName本当に ? を使用しますclassloaderか? もしそうなら、どの方法ですか?ネイティブ呼び出しを使用しているように見えるので、裏で何をしているのかわかりません。

もちろん、誰かがClass.forName()呼び出しをテストする別の方法を知っていれば、それも大歓迎です。

4

1 に答える 1

0

Class.forName()呼び出されたクラスのクラスローダーを使用します(たとえば、test()メソッドを含むクラスの場合)。そのため、別の環境で実行している場合、これが問題の原因になります。

更新その ClassLoader はClass.forName()、クラスをロードした場所で使用されますTest。そして、それが解決策かもしれません。それは、クラスにアクセスできるEclipse定義のクラスローダーである可能性があるため、それをロードします。その親 (またはルート) クラスローダーには、そのクラスのロードを禁止する明示的な規則があります。

このインスタンス化のラッパー クラスを作成することをお勧めします。そのクラスを でロードする必要がありますCustomTestClassLoader。その後、そのクラスで使用できますClass.forName()

于 2013-01-16T12:00:18.637 に答える