编译日期和时间

kod*_*v19 4 java compile-time

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

谢谢

kodev19

SRG*_*SRG 6

据我所知,没有类似的东西.但是在运行的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;
}
Run Code Online (Sandbox Code Playgroud)

将输出一次使用的东西(这里为2008年3月15日20:43编译的commons-lang-2.4.jar中可用的StringUtils.class):

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