java - Java中声明静态常量会影响编译后的类

标签 java static constants

好吧,这是我的疑问......

我有一个 blazeDS (tomcat) 应用程序,其中包含一些类,每个类都使用 ConfigDB 类进行配置和数据库连接...

这是一个示例

配置

public class Config {
    public static final String DBClass = "oracle.jdbc.driver.OracleDriver";
    public static final String ConnectString = "jdbc:oracle:thin:@//127.0.0.1:1521/xe";
    public static final String UserDB = "user";
    public static final String PasswordDB = "pass"; 
}

数据库

public class DB
{       
    public DB() {}

    public static Connection dbConnect(Connection c)
    {
                try
                {      if (c == null || c.isClosed()){                                  
                            Class.forName(Config.DBClass);
                            c = DriverManager.getConnection(Config.ConnectString,Config.UserDB,Config.PasswordDB);
                        }
                return c;                        
                }
                catch (Exception e)
                {
                        System.out.println(e.getMessage());
                        return null;
                }
    }

    public static void closeConnection(Connection connection) throws SQLException
    {
        if (!connection.isClosed())
            connection.close();
    }
}

我有一个测试和生产环境,每个数据库访问都有不同的用户/密码。 我注意到,当使用测试类更新生产文件时(我不覆盖 Config.class ),我从数据库收到错误...

那么,编译版本中的静态最终值(用户/密码)是否直接保存在类本身中(在我的例子中是DB.class)???

最佳答案

简而言之,是的。

摘自Java specs :

"References to fields that are constant variables (§4.12.4) are resolved at compile-time to the constant value that is denoted. No reference to such a field should be present in the code in a binary file (except in the class or interface containing the field, which will have code to initialize it). Such a field must always appear to have been initialized (§12.4.2); the default initial value for the type of such a field must never be observed. See §13.4.9 for a discussion." (p. 339)

关于java - Java中声明静态常量会影响编译后的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11736580/

相关文章:

c - 指向 const 的指针是否与 __restrict 具有相同的效果?

java - Sonarqube 插件矩阵显示 LTS 6.7.2 有 SonarJava 5.1.1,但似乎没有

java - Netbeans:访问静态字段 - 替换为类引用

java - Java中的Itext PDF操作

c++ - C++ static 与 C 中的 static 相同吗?

php - 什么时候使用 self、parent、static 以及如何?

c++ - 为什么在运行时而不是在编译时使用 constexpr 初始化变量

java - 安卓 Java : can switch statement avoid inlining when creating a secret string?

java - RMI 服务器 - 模块 RMIServer 没有 "exports Server"到模块 java.rmi

java.sql.BatchUpdateException : ORA-01849: hour must be between 1 and 12