java static initializer called twice

☆樱花仙子☆ 提交于 2019-12-25 05:46:09

问题


static boolean isClassLoaded(String fullname) {
    try {
        Class.forName(fullname, false, Loader.instance().getModClassLoader());
        return true;
    } catch (Exception e) {
        return false;
    }
}

does this method has potential to trigger fullname's static initializer ? i have problem with static initializer called twice. when i try to check if class loaded using isClassLoaded and try to use that class, i get error because of constructor called twice. anyone know what is problem with Class.forName(fullname, false, Loader.instance().getModClassLoader()); ?


回答1:


The second parameter is a flag called "initialize".

From the docs:

The class is initialized only if the initialize parameter is true and if it has not been initialized earlier.

So, if initialize is set to false, it will not execute your static initializers.

Self-contained example

package test;

public class Main {

    public static void main(String[] args) throws Exception {
        Class.forName("test.Main$Foo", false, Main.class.getClassLoader());
        System.out.println("blah");
        Class.forName("test.Main$Foo", true, Main.class.getClassLoader());
    }

    static class Foo {
        static {
            System.out.println("Foo static initializer");
        }
    }

}

Output

blah
Foo static initializer

Note it would always print Foo static initializer only once, but here, it prints blah first, i.e. the first Class.forName invocation did not execute the static initializer.



来源:https://stackoverflow.com/questions/33040829/java-static-initializer-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!