Class.forName()-还有其他使用方式吗? [英] Class.forName() - are there other ways to use it?

查看:249
本文介绍了Class.forName()-还有其他使用方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此线程连续:
无法连接Apache 7.0上的hypersonic(HSQLDB)数据库

我需要知道是否还有其他使用 Class.forName( )函数。

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

是否可以从某个jar中加载类?

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

推荐答案

对于JDBC和其他服务(就应用程序的服务而言,不是OSGI服务),存在 ServiceLoader ,它将根据类路径加载类,并且如果类路径上的任何jar文件提供

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.

较旧的方法有一个DriverManager,它基本上是可能服务的集合。这是您的示例中显示的模式,其中创建类的实例通常会强制静态初始化程序块运行。该块通常看起来像。

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());
  } 
}

或特别是对于JDBC

or for JDBC in particular

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

在JDBC中,驱动程序管理器然后遍历注册服务,询问每个服务是否提供 jdbc:hsqldb:hsql:// ...连接字符串的连接。

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.

如果您不能依靠静态初始化程序块,尤其是在处理JDBC时,您可以(假设可以以某种方式加载类)调用方法,使用registerDriver(...)在DriverManager中注册实例。但是,您可以轻松看到所涉及的模式。

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.

这篇关于Class.forName()-还有其他使用方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆