2016-09-02 9 views
0

美好的一天,团队。 我有一个简单的gradle项目,它带有Java“HelloWorld”类到PoC。可执行Jar文件生成期间更改班级内的数据

public class HelloWorld { 
public static void main (String[] args){ 
    String hello = "Hello, world"; 
    System.out.print(hello); 
}} 

我已经为此类生成了可运行Jar文件。 现在我想下一步该怎么做:Jar文件生成过程中的gradle中,我需要改变“你好,世界”“你好另一个世界”。我知道这是可能的,但我无法在网上找到这些信息。 在此先感谢。 当前gradle这个代码是波纹管:

apply plugin: 'java' 
apply plugin: 'application' 

sourceCompatibility = 1.5 

repositories { 
    mavenCentral() 
} 

dependencies { 
    testCompile group: 'junit', name: 'junit', version: '4.11' 
} 

task createJar(type: Jar){ 
    mainClassName = 'HelloWorld' 
    manifest {attributes 'Implementation-Title': 'Gradle Jar File Example','Main-Class': mainClassName} 
    baseName = 'HelloWorldJar' 
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    with jar 
} 
+0

过滤原始源文件是不是一个好主意。提供不同的属性文件要好得多。 – Opal

+0

如果您想更改源文件HelloWorld.java或者您是否希望更改已编译的字节码文件HelloWorld.class,能否请您解释一下? –

+0

第二个,改变编译好的字节码文件HelloWorld.class –

回答

0

嗯,我自己做到了。可能不是最聪明的解决方案,但仍然工作:)谢谢谁试图帮助我。下面

task copyJavaClass(type: Copy) { 
    from 'src/main/java' 
    into 'src/main/java' 
    include 'HelloWorld.java' 
    filter { line -> !line.contains('String hello = "Hello, world";') ? line : 'String hello = "Hello another world";' } 
    filter { line -> !line.contains('public class HelloWorld {') ? line : 'public class HelloAnotherWorld {' } 
    rename { filename ->filename.replace 'HelloWorld', 'HelloAnotherWorld' 
    } 
} 

task createJar(type: Jar){ 
    mainClassName = 'HelloAnotherWorld' 
    manifest {attributes 'Implementation-Title': 'Gradle Jar File Example','Main-Class': mainClassName} 
    baseName = 'HelloAnotherWorldJar' 
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    with jar 
} 

首要任务变化与类名和符合字符串全线

更新的代码,第二个创建新类运行的JAR文件。 在终端中运行gradlew copyJavaClass createJar任务。