使用java-6和java-7部分编译gradle项目

使用java-6和java-7部分编译gradle项目,java,gradle,Java,Gradle,我想用java6和java7编译项目中的一些代码。我似乎无法为不同的源集分配不同的源/目标兼容性。我知道这是一个奇怪的设置,但是java7代码依赖于一些java7库,java6代码必须由其他java6代码加载(我无法控制) 我一直在尝试使用一个子项目 java7-project \build.gradle (compatibility = 1.7, compile project(':java6-submodule')) \settings.gradle \java6-module

我想用java6和java7编译项目中的一些代码。我似乎无法为不同的源集分配不同的源/目标兼容性。我知道这是一个奇怪的设置,但是java7代码依赖于一些java7库,java6代码必须由其他java6代码加载(我无法控制)

我一直在尝试使用一个子项目

java7-project
 \build.gradle (compatibility = 1.7, compile project(':java6-submodule'))
 \settings.gradle
 \java6-module
    \build.gradle (compatibility = 1.6)
这实际上工作得很好,但是,我希望在创建jar时将java6模块作为java7项目的一部分。我也可以这样做。。。使用(来自互联网的一些代码)

然而,当我运行:install任务将库放入本地maven repo时,生成的POMforJava7项目对“java6模块”具有编译依赖性


我希望能够用不同的java版本编译代码的不同部分,同时将其作为一个模块处理(或模拟行为)?

我最终按照Peter的建议为我的java6代码使用了一个单独的源代码集,并向构建文件中添加如下内容:

sourceSets {
  java6Src // new source set
  main { // make sure our new source set is included as part of the main so it compiles and runs
    compileClasspath += java6src.output
    runtimeClasspath += java6Src.output
  }
}

compileJava6SrcJava { // set the compile options
  sourceCompatibility = 1.6
  targetCompatibility = 1.6
  // if jdk6.home is defined use it for compatibility
  def jdk6Home = System.properties['jdk6.home']
  if(jdk6Home) {
    options.bootClasspath = (new File(jdk6Home,"/jre/lib/rt.jar")).canonicalPath
  }
}


jar { // include java6Src set in the jar 
  from {
    sourceSets.java6Src.output
  }
}

我不认为将Java 6和Java 7代码放在同一个Jar中有什么意义,但您总是可以声明一个具有不同源/目标兼容性的附加
JavaCompile
任务,并将
Jar
任务配置为包含其输出。我希望不必这样做。我不介意包含子项目jar,但我也不想要fatjar,我想将其排除在主项目的ivy/maven依赖项之外。除了声明额外的
JavaCompile
任务外,还可以声明额外的源代码集,它有自己的免费
JavaCompile
任务。所以我必须做一些像sourceset.getJavaCompileTask这样的事情来配置它?听起来不错,我来试试。你可以做
compileSourceSetNameJava{…}
sourceSets {
  java6Src // new source set
  main { // make sure our new source set is included as part of the main so it compiles and runs
    compileClasspath += java6src.output
    runtimeClasspath += java6Src.output
  }
}

compileJava6SrcJava { // set the compile options
  sourceCompatibility = 1.6
  targetCompatibility = 1.6
  // if jdk6.home is defined use it for compatibility
  def jdk6Home = System.properties['jdk6.home']
  if(jdk6Home) {
    options.bootClasspath = (new File(jdk6Home,"/jre/lib/rt.jar")).canonicalPath
  }
}


jar { // include java6Src set in the jar 
  from {
    sourceSets.java6Src.output
  }
}