java两次调用静态初始化程序 [英] java static initializer called twice

查看:219
本文介绍了java两次调用静态初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

此方法是否有可能触发全名的静态初始值设定项? 我有两次调用静态初始化程序的问题. 当我尝试检查是否使用isClassLoaded加载的类并尝试使用该类时,由于构造函数调用了两次,因此出现错误. 任何人都知道Class.forName(fullname,false,Loader.instance().getModClassLoader())有什么问题; ?

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

推荐答案

第二个参数是一个名为"initialize"的标志.

The second parameter is a flag called "initialize".

仅当initialize参数为true且初始化时,类才被初始化 如果尚未提前初始化.

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

因此,如果initialize设置为false,它将不会执行静态初始化程序.

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

自包含示例

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

}

输出

blah
Foo static initializer

请注意,它始终只打印一次Foo static initializer,但是在这里,它先打印blah,即第一次Class.forName调用未执行静态初始化程序.

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.

这篇关于java两次调用静态初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆