如何在Java中声明全局静态类?

Pen*_*m10 3 c# java

在C#中,我可以创建一个这样的类:

static class clsDBUtils
{
        public static SQLiteCommand cmd;
        public static SQLiteConnection conn;
        public static String databaseFilePath;

        public static bool getConnection()
        {
        }
}
Run Code Online (Sandbox Code Playgroud)

然后我的命名空间中的任何地方都可以使用这种方式进

clsDBUtils.getConnection();
Run Code Online (Sandbox Code Playgroud)

如何为Java重写?

我不想用:

clsDBUtils sqlutil= new clsDBUtils();
Run Code Online (Sandbox Code Playgroud)

Luc*_*ero 9

基本上以相同的方式,只需final使用私有构造函数创建(正常)类(阻止能够执行new)并仅添加静态成员.

public final class clsDBUtils {
    public static SQLiteCommand cmd;
    public static SQLiteConnection conn;
    public static String databaseFilePath;

    public static bool getConnection() {
    }

    private clsDBUtils() {}
}
Run Code Online (Sandbox Code Playgroud)

  • @ Pentium10:防止课程延长; 如果它可以扩展,那么它可以实例化. (3认同)

Bal*_*usC 5

除了特定的问题/问题之外,声明昂贵的外部资源是不好的做法Connection,Statement并且ResultSet作为实例变量,更不用说作为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;
}
Run Code Online (Sandbox Code Playgroud)

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以用它了

connection = Database.getConnection();
Run Code Online (Sandbox Code Playgroud)

(使用后你仍然需要在finally块中关闭!)

但是,这使得连接源也非常静态.您不能再利用多态性和/或继承来在连接源之间切换,例如连接池(以获得更好的性能).要获得更多想法/见解,您可能会发现本文很有用