我在Java项目中有两个软件包。
Package A
具有一个称为App.java
的类。此类接受参数解析(利用apache commons-cli lib)。
代码是
CommandLineParser clip = new DefaultParser();
Options options = new Options();
options.addOption("zp", "ZipFilePath", true, "Mention the path where zip file is present");
options.addOption("d", "dbPropFile", true, "Mention the path database property file");
options.addOption("h", "help", false, "This mentions how to use this utility");
CommandLine cli = clip.parse(options, args);
File dbpropFile = new File(cli.getOptionValue("d"));
现在如何在程序包B的另一个类(SQLServerConn.java)中导入dbPropFile
变量?
package com.abc.integra.db.B;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import com.abc.integra.db.A.LoadDBProps;
public class SQLServerConn {
public static Connection dbConn;
public static Properties props;
public static Connection getConn() {
try {
final String drivername = (String)SQLServerConn.props.get("drivername");
final String url = (String)SQLServerConn.props.get("url");
final String dbname = (String)SQLServerConn.props.get("dbname");
final String username = (String)SQLServerConn.props.get("username");
final String password = (String)SQLServerConn.props.get("password");
//jasypt final String password1 = (String)SQLServerConn.props.getProperty(key);
Class.forName(drivername); //registering the driver before connection with the DB
SQLServerConn.dbConn = DriverManager.getConnection(url + ";databaseName=" + dbname + ";user=" + username + ";password=" + password);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return SQLServerConn.dbConn;
}
static {
SQLServerConn.dbConn = null;
try {
final LoadDBProps lp = new LoadDBProps();
SQLServerConn.props = lp.loadDBProperties(filename);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我想用dbpropFile
变量值代替负荷属性部分中的filename
。
您必须提供完整的路径来导入该类。例如:
import xx.A.App;
现在您可以访问App类,您可以使用以下任一方法:
1)用于访问其public类成员(composition),
的App对象class App {
File dbPropFile;
CommandLineParser clip = new DefaultParser();
public void setDbPropFile (String fileOption) {
this.dbPropFile = new File(clip.getOptionValue(fileOption));
}
public File getDbPropFile () {
return dbPropFile;
}
}
public class SQLServerConn {
App app = new App();
app.setDbPropFile("d");
SQLServerConn.props = lp.loadDBProperties(app.getDbPropFile());
}
2)直接类名,以访问static和public类成员。
class App {
static File dbpropFile = new File(cli.getOptionValue("d"));
}
class SQLServerConn {
SQLServerConn.props = lp.loadDBProperties(App.dbpropFile); // exact class name to access static variable
}
如果要求仅导入单个属性dbpropFile
,则在Java中是不可能的。