如何在Java中声明全局静态类?
在C#中,我可以创建一个这样的类:
static class clsDBUtils { public static SQLiteCommand cmd; public static SQLiteConnection conn; public static String databaseFilePath; public static bool getConnection() { } }
然后我的命名空间中的任何地方都可以使用这种方式进
clsDBUtils.getConnection();
如何为Java重写?
我不想用:
clsDBUtils sqlutil= new clsDBUtils();
基本上以同样的方式,只需使用私有构造函数创建(正常) final
类(阻止能够执行new
)并仅添加静态成员。
public final class clsDBUtils { public static SQLiteCommand cmd; public static SQLiteConnection conn; public static String databaseFilePath; public static bool getConnection() { } private clsDBUtils() {} }
除了特定的问题/问题之外,将Connection
, Statement
和ResultSet
等昂贵的外部资源Statement
为实例变量是不好的做法 ,更不用说作为static
变量了。 这些资源没有无限的生命周期,当DB决定超时连接时,您的应用程序可能会中断,因为它在使用后尚未释放回DB。
我无法想象它在C#中的表现有所不同(它本来也是应用程序中的一个错误),但正常的JDBC习惯用法是你在尽可能短的范围内获取和关闭它,因此已经在同一个方法中块。 例如
public Entity find(Long id) throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; Entity entity = null; try { connection = database.getConnection(); statement = connection.prepareStatement(SQL_FIND); statement.setLong(1, id); resultSet = statement.executeQuery(); if (resultSet.next()) { entity = new Entity(); entity.setProperty(resultSet.getObject("columnname")); // etc.. } } finally { // Always free resources in reversed order. if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {} if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {} if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {} } return entity; }
但是,在技术上, database.getConnection()
可以完美地变为静态,如下所示:
public final class Database { static { try { Class.forName("com.example.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new ExceptionInInitializerError(e); } } private Database() { // No need to instantiate this class. } public static Connection getConnection() { DriverManager.getConnection("jdbc:example://localhost/dbname", "user", "pass"); } }
这样你就可以用它了
connection = Database.getConnection();
(使用后你仍然需要在finally
块中关闭!)
但是,这使得连接源也非常静态 。 您不能再利用多态性和/或inheritance来在连接源之间切换,例如连接池(以获得更好的性能)。 要获得更多想法/见解,您可能会发现本文很有用
它的代码几乎完全相同(相同的概念,略有不同的语法)
public class ClsDBUtils { public static SQLiteCommand cmd; public static SQLiteConnection conn; public static String databaseFilePath; public static boolean getConnection() { } } // somewhere else ClsDBUtils.getConnection();
只需声明一个公共类,并在方法和字段上使用’static’修饰符。 如果您不希望它被实例化,请使用“public final class”。 或者,您可以使用单例类。
您想要实现Singleton模式: http : //en.wikipedia.org/wiki/Singleton_pattern
public class clsDBUtils { private static final clsDBUtils INSTANCE = new clsDBUtils(); // Private constructor prevents instantiation from other classes private clsDBUtils() {} public static clsDBUtils getInstance() { return INSTANCE; } public SQLiteCommand cmd; public SQLiteConnection conn; public String databaseFilePath; public bool getConnection() { } }
然后,您可以在类上使用以下语法:
clsDBUtils.getInstance().getConnection();