相关疑难解决方法(0)

有没有办法在编译时为Java定义一个常量值

当我以前用C/C++编写库时,我养成了使用方法返回编译日期/时间的习惯.这总是被编译到库中,因此可以区分库的构建.我通过在代码中返回#define得到了这个:

C++:

#ifdef _BuildDateTime_
   char* SomeClass::getBuildDateTime() {
      return _BuildDateTime_;
   }
#else
   char* SomeClass::getBuildDateTime() {
      return "Undefined";
   }
#endif
Run Code Online (Sandbox Code Playgroud)

然后在编译时我有一个'-D_BuildDateTime_ =Date在构建脚本中 '.

有没有办法在Java中实现这个或类似的,而无需记住手动编辑任何文件或分发任何单独的文件.

我从同事那里得到的一个建议就是让ant文件在类路径上创建一个文件并将其打包到JAR中并让它通过该方法读取.

类似的东西(假设创建的文件名为'DateTime.dat'):

// I know Exceptions and proper open/closing 
// of the file are not done. This is just 
// to explain the point!
String getBuildDateTime() {
    return new BufferedReader(getClass()
            .getResourceAsStream("DateTime.dat")).readLine();
}
Run Code Online (Sandbox Code Playgroud)

在我看来,这是一个黑客,可以被外面有类似命名文件的人规避/破坏在JAR,但是在类路径上.

无论如何,我的问题是在编译时是否有任何方法将一个常量注入一个类

编辑

我考虑在JAR中使用外部生成的文件的原因是因为这一个库并将嵌入到客户端应用程序中.这些客户端应用程序可能会定义自己的类加载器,这意味着我不能依赖标准的JVM类加载规则.

我个人的偏好是使用serg10建议的JAR文件中的日期.

c c++ java

12
推荐指数
2
解决办法
6329
查看次数

标签 统计

c ×1

c++ ×1

java ×1