【问题标题】:Compile date and time编译日期和时间
【发布时间】:2010-12-27 10:10:06
【问题描述】:

是否存在与 C 和 C++ 编译时常量 __DATE__ 和 __TIME__ 等效的 Java。我需要打印正在编译的程序的编译时间和版本信息。

谢谢

kodev19

【问题讨论】:

  • 编译时约束意味着时间戳必须嵌入到 Java 源文件中,而不是存储在外部文本文件中。
  • @Dave - 我不确定情况是否如此,是吗?您不能在编译开始之前在其他地方记录编译时间吗(我意识到这并不完全准确,但是...)

标签: java compile-time


【解决方案1】:

据我所知,没有这样的事情。 但是在正在运行的 JVM 上,您可以使用以下代码直接从 jar 中获取一些信息(这里,信息来自编译时放入 jar 中的 Manifest 文件(无论您的构建系统是 Ant 还是 Maven或其他任何东西)。随意调整它(不同的输出,等等)。

    public String getVersionfinal Class classe) {
    String version = null;
    String shortClassName = classe.getName().substring(classe.getName().lastIndexOf(".") + 1);
    try {
        ClassLoader cl = this.getClass().getClassLoader();
        String threadContexteClass = classe.getName().replace('.', '/');
        URL url = cl.getResource(threadContexteClass + ".class");
        if ( url == null ) {
            version = shortClassName + " $ (no manifest)";
        } else {
            String path = url.getPath();
            String jarExt = ".jar";
            int index = path.indexOf(jarExt);
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            if (index != -1) {
                String jarPath = path.substring(0, index + jarExt.length());
                File file = new File(jarPath);
                String jarVersion = file.getName();
                JarFile jarFile = new JarFile(new File(new URI(jarPath)));
                JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
                version = shortClassName + " $ " + jarVersion.substring(0, jarVersion.length()
                        - jarExt.length()) + " $ "
                        + sdf.format(new Date(entry.getTime()));
                CloseHelper.close(jarFile);
            } else {
                File file = new File(path);
                version = shortClassName + " $ " + sdf.format(new Date(file.lastModified()));
            }
        }
    } catch (Exception e) {
        version = shortClassName + " $ " + e.toString();
    }
    return version;
}

使用后会输出类似的东西(这里是 2008 年 3 月 15 日 20:43 编译的 commons-lang-2.4.jar 中可用的 StringUtils.class):

StringUtils $ commons-lang-2.4 $ 15/03/2008 20:43:16

【讨论】:

    【解决方案2】:

    Ant TStamp 任务在这里很有用。它会在构建期间创建一个时间戳,以便插入到属性文件或代码中。

    设置 DSTAMP、TSTAMP 和 TODAY 当前项目中的属性。经过 默认情况下,DSTAMP 属性位于 格式“yyyyMMdd”,TSTAMP 在 格式为“hhmm”,TODAY 位于 格式“MMMM dd yyyy”。使用嵌套 指定一个元素 不同的格式。

    这些属性可以用在 构建文件,例如,创建 带时间戳的文件名,或用于 替换里面的占位符标签 文件以表明,例如, 发布日期。最好的地方 这个任务可能在 初始化目标。

    我倾向于使用它来构建一个包含构建时间和日期、用户和主机、版本号等的属性文件,然后我的应用程序读取该属性文件并记录相关信息(我通常不在我担心人们会摆弄这些信息的环境)。

    【讨论】:

      【解决方案3】:

      不是直接在代码中,不,但是你可以使用 Ant 来做这个。

      请参阅this page 上的“袋熊”示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多