可以诱使javah生成具有一致行结尾的.h文件吗



我有一个maven项目,它通过执行javah来生成.h JNI文件,这是java库的正常构建过程的一部分。然后将这些.h文件签入到源代码管理(如git(中,并用于构建附带的本机库。

一个小麻烦是javah生成的文件因其运行平台的不同而不同。因此,如果Mac OSX开发人员运行构建并签入(UNIX样式的行结尾(,则Windows开发人员随后会看到他们的构建已将所有.h文件更改为Windows样式的行末尾。但它们实际上并没有改变——javah只是以一种依赖于平台的方式运行。

例如,在生成.h文件时,如何说服javah始终使用UNIX样式的行结尾?似乎没有合适的命令行开关:

> javah.exe
Usage:
  javah [options] <classes>
where [options] include:
  -o <file>                Output file (only one of -d or -o may be used)
  -d <dir>                 Output directory
  -v  -verbose             Enable verbose output
  -h  --help  -?           Print this message
  -version                 Print version information
  -jni                     Generate JNI-style header file (default)
  -force                   Always write output files
  -classpath <path>        Path from which to load classes
  -bootclasspath <path>    Path from which to load bootstrap classes
<classes> are specified with their fully qualified names
(for example, java.lang.Object).

也许可以手动启动与javah可执行文件启动相同的类,但在此之前要显式设置"line.separator"属性。但是,我找不到该是什么类,也找不到在哪里。

'javah'在这方面与其他Java程序相同。行终止符是由例如PrintWriter.println((编写的,由系统属性"line.separator"决定。你可以尝试从命令行设置它,但我怀疑你这样做会带来任何乐趣。我会寻找一个更横向的解决方案,比如按照建议重新配置IDE,或者只在一台构建机器上运行javap。

我通过编写一个明确设置line.separator属性的自定义启动器来解决这个问题,然后在构建过程中调用该启动器:

public class JavahLauncher {
    public static void main(String[] args) {
        String original = System.getProperty("line.separator");
        System.setProperty("line.separator", "n");
        try {
            com.sun.tools.javah.Main.run(args, new PrintWriter(System.out));
        }
        finally {
            System.setProperty("line.separator", original);
        }
    }
}

try最终允许在执行构建时在另一个JVM(例如Maven的JVM实例(内调用此启动器,而无需永久更改line.separator值。一个有趣的注意事项是com.sun.tools.javah.Main.main不可用,因为它调用System.exit,如果作为Maven构建的一部分进行调用,则会导致Maven退出!

编译这个启动器需要依赖tools.jar,类似于:

<dependency>
    <groupId>com.sun</groupId>
    <artifactId>tools</artifactId>
    <version>1.7.0</version>
    <scope>system</scope>
    <systemPath>${java.home}/../lib/tools.jar</systemPath>
</dependency>

最新更新