【发布时间】:2015-09-28 07:31:31
【问题描述】:
我在一个旧项目中找到了这段代码
public abstract class AireBatchDaoFactory {
public static final String ORACLE_FACTORY = "airebatch.oracle.OracleDaoFactory";
public static AireBatchDaoFactory getFactory(String factory) throws SQLException
{
try {
return (AireBatchDaoFactory) Class.forName(factory).newInstance();
}
catch (Exception e) {
throw new SQLException("error msg");
}
}
public abstract AireBatchDao getAireBatchDao() throws SQLException;}
我想了解两者之间的具体区别
return (AireBatchDaoFactory) Class.forName(factory).newInstance();
和
return new AireBatchDaoFactory();
【问题讨论】:
-
它叫做反射。有一个
String描述了class的FQCN,代码尝试首先将String转换为Class实例,然后再转换为class的新实例,假设默认构造函数。这是从String创建实例的唯一方法 -new显然在这里不起作用。 -
只写
return class.forName(factory).newInstance();可能是通用的,其余的似乎相同。还捕获超级Exception并抛出SQLException而不是ClassNotFoundException,也许有人会在一段时间内改变这一点。甚至没有使用变量ORACLE_FACTORY -
此外,通常这些工厂是无法实例化的 抽象类 (在您的情况下也是如此)。强制转换是实现方法签名所必需的(也可能失败)。
-
@ankur-singhal 它是
public static final- 意图大概是传递给 API 的默认值,异常处理对于 JDBC 代码来说是非常正常的 - 重新抛出SQLException使处理使用 JDBC API 时代码一致。
标签: java reflection factory