Class.forName() - are there other ways to use it?

荒凉一梦 提交于 2019-12-11 11:07:00

问题


Continuously this thread: Failed to connect hypersonic(HSQLDB) DB on Apache 7.0

I need to know if there are some other new ways to use Class.forName() function.

Is there a way to load a class from a certain jar ?


回答1:


For JDBC and other services (in the sense of services to the application, not OSGI services), there is ServiceLoader which will load classes based on the classpath, and if any of the jar files on the classpath offer to provide "implementations" of the "abstract" service.

Older ways have a DriverManager, which is basically a Collection of possible services. This is the pattern being shown in your example, where creating an instance of the class typically forces the "static initializer" block to run. That block will typically look something like.

public class MyService implements Service {
  static {
     ServiceRegistry.register(new MyService());
  } 
}

or for JDBC in particular

public class MyDriver implements Driver{
  static {
     DriverManager.registerDriver(new MyDriver());
  } 
}

In JDBC the driver manager then goes through the list of registered services, asking each one if they provide connections for the "jdbc:hsqldb:hsql://...." connection string.

If you cannot rely on the static initializer block, and you're dealing with JDBC in particular, you can (assuming you can load the class somehow) call the methods to register an instance in the DriverManager, with registerDriver(...); but, you can easily see the patterns involved.



来源:https://stackoverflow.com/questions/32106052/class-forname-are-there-other-ways-to-use-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!