Class.forName()vs ClassLoader.loadClass() - 用于动态加载? [英] Class.forName() vs ClassLoader.loadClass() - which to use for dynamic loading?
问题描述
动态加载类时,何时适合使用
When dynamically loading a class, when is it appropriate to use
Class.forName("SomeClass");
我应该何时使用
ClassLoader.getSystemClassLoader().loadClass("SomeClass");
或者,他们有两种方法做同样的事情吗?
Or, are they two ways of doing the same thing?
推荐答案
它们完全不同!
返回与具有给定字符串名称的类或接口关联的Class对象。调用此方法相当于:
Class.forName(className,true,currentLoader)
( true
这里是指你想要初始化课程吗?)
另一方面, ClassLoader.loadClass(String)
:
On the other hand, ClassLoader.loadClass(String)
:
调用此方法相当于调用
loadClass(name,false)
。
(这里,布尔值与初始化无关;但是如果检查loadClass(String,boolean)文档,你会看到它所做的只是加载类,而不是初始化它。)
(here, the boolean has nothing to do with initialization; but if you check loadClass(String, boolean) documentation, you will see that all it does is load the class, not initialize it).
第一个( Class.forName(SomeClass);
)将:
- 使用加载了调用此代码的类的类加载器
- 初始化类(即所有sta)将运行tic初始化程序)
另一个( ClassLoader.getSystemClassLoader()。loadClass(SomeClass) ;
)将:
- 使用system类加载器(哪些可以覆盖)
- 没有初始化类(比如说,如果你用它来加载JDBC驱动程序,它就赢了' t注册,你将无法使用JDBC!)
假设您正在编写将要执行的Web应用程序在像Tomcat这样的容器上。 Tomcat所做的是为每个Web应用程序创建一个类加载器(以便以后可以卸载Web应用程序并释放内存 - 您需要一个专用的类加载器才能实现此功能!)。在这种情况下,您可以看到两个调用都会产生完全不同的结果!
Suppose you are coding a web application that will be executed on a container such as Tomcat. What Tomcat does is create a class loader for each web application (so that it can unload the webapps later and release memory -- you need a dedicated class loader for this to work!). In this situation, you can see that both calls will yield quite different results!
有关类加载和初始化的更详细(和权威)信息,请检查 12.2 和 12.4 语言规范。
For more detailed (and authoritative) information on class loading and initialization, check sections 12.2 and 12.4 of the latest (3rd) edition of the Java Language Specification.
这篇关于Class.forName()vs ClassLoader.loadClass() - 用于动态加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!