What does Class.forName(); do?

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值