简体   繁体   English

java动态类加载

[英]java Dynamic class loading

When loading the class, using method forName() , any static initializers in the class are executed. 使用方法forName()加载类时,将执行该类中的所有静态initializers Can I prevent this ? 我可以预防吗?

try {
        Class.forName("MYClass");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

MyClass 我的课

class MyClass{

static String TEST="MYCLASS";
static SomeClass sm=new SomeClass();
}

I found in doc that there is a overloaded version of Class.forName() ie 我在文档中发现Class.forName()的重载版本,即

public static Class<?> forName(String name,
                           boolean initialize,
                           ClassLoader loader)
                    throws ClassNotFoundException

What is initialize parameter ? 什么是initialize参数?

This is how Java creates objects, so no. 这就是Java创建对象的方式,所以没有。 One way would be to lazy load the instances at some other time. 一种方法是在其他时间延迟加载实例。

This would imply you would have to remove the static reference. 这意味着您将必须删除静态引用。

eg 例如

public SomeClass getSomeClass() {
   if (sm == null) {
      return new SomeClass();
   }

   return sm;

}

If you dont want to execute static initialization try class literal instead of Class.forName 如果您不想执行静态初始化,请尝试使用类文字而不是Class.forName

class A1{
    static{
        System.out.println("static block from A1");
    }
}

class B1{
    public static void main(String[] args) throws ClassNotFoundException {
//      Class.forName("A1");//this will invoke static initialization
        Class c=A1.class;//this will not invoke static initialization
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM