您的位置:首页 > 其它

What does Class.forName(); do?

2010-12-27 16:23 513 查看
Question:
What exactly does the
Class.forName();

statement do? Why is this construct encountered only with JDBC? (I have not seen any code that uses
Class.forName()

in other contexts.)

Answer:
Every object has a corresponding class object. This class object instance is shared among all instances of that class type.

Class.forName()

loads and returns the class object for the given class name. So, for example, if you write:

Class object = Class.forName("java.io.FileNotFoundException");


the JVM will load and return the class object for
FileNotFoundException

. Class objects play an important role in reflection. For example, you may call:

try

{

Class object = Class.forName("java.io.FileNotFoundException");Object ex = object.newInstance();

}

catch (ClassNotFoundException ex) {}

catch (InstantiationException ex) {}

catch (IllegalAccessException ex) {}



In the example above,
newInstance()

goes out and instantiates an object for class if it has a no arguments constructor. You can also use the class object to
obtain field, method, and interface information.

The example given above is a bit contrived.
However, let's say you define an interface that provides a proxy to some
backend
server. Your program knows how to manipulate the
interface; it does not, however, know which interface implementation to
instantiate
at compile time. Instead, you provide that class
name as a command line argument. Your program can use reflection to go
out
and instantiate that object.

In the case of JDBC, the
Class.forName()

loads the JDBC driver into the JVM.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: