Multiple instances of static variables

前端 未结 4 1302
自闭症患者
自闭症患者 2021-02-13 14:42

I\'m experimenting with using different classloaders to load a particular class, and see if the static variables in that class can have different instances.

Basically,

4条回答
  •  感动是毒
    2021-02-13 15:44

    It looks as though the class "A" is being loaded by the parent class loader, rather than your CustomClassLoader (because you call super.loadClass).

    The following untested amendment should allow you to define the "A" class using your own class loader (while delegating everything else to the parent loader).

    Apologies for the horrible bodge where I assume the single inputStream.read() will read everything! But you can hopefully see what I mean.

        public Class loadClass(String classname)  throws ClassNotFoundException {
        if (classname.equals("A")) {
            InputStream is = getResourceAsStream("A.class");
            byte[] bodge = new byte[8192];  // Should read until EOF
            try {
                int len = is.read(bodge);
                return defineClass("A", bodge, 0, len);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        return super.loadClass(classname, true);
    }
    

    You'll probably then end up with ClasscastExceptions or something similar...

提交回复
热议问题