Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store method parameter names for some classes when building with Gradle/Java8

Follow up question to this question.

How do I store method parameter names for classes when building with Gradle (build.gradle file)?

According to Java tutorials:

To store formal parameter names in a particular .class file, and thus enable the Reflection API to retrieve formal parameter names, compile the source file with the -parameters option to the javac compiler.

So How do I pass the "-parameters" to the javac compiler using Gradle?

I tried the suggested solution here, by adding the below into my build.gradle file with no luck.

apply plugin: 'java'

compileJava {
    options.compilerArgs << '-parameters'
    options.fork = true
    options.forkOptions.executable = 'javac'
}

I'm using eclipse and if I enable this (in Window -> Preferences -> Java -> Compiler), it works fine.

Store information about method parameters (usable via reflection)

But I would rather have this setting set by my build system, so i don't depend on eclipse and so others can use my buildt .jar files.

I use:

  • Eclipse 4.4.2
  • Gradle IDE 3.6.4 (eclipse plugin)
like image 686
etxalpo Avatar asked Mar 14 '15 11:03

etxalpo


2 Answers

To get gradle itself to compile with -parameters add the following to your build.gradle:

compileJava.options.compilerArgs.add '-parameters'
compileTestJava.options.compilerArgs.add '-parameters'

In order to use Gradle to generate Eclipse project files where -parameters is set for javac: Use a tip from this gradle forum post and add the following to your build.gradle:

eclipseProject {
  doLast {
    // https://discuss.gradle.org/t/how-to-write-properties-to-3rd-party-eclipse-settings-files/6499/2

    def props = new Properties()
    file(".settings/org.eclipse.jdt.core.prefs").withInputStream {
      stream -> props.load(stream)
    }
    props.setProperty("org.eclipse.jdt.core.compiler.codegen.methodParameters", "generate")
    file(".settings/org.eclipse.jdt.core.prefs").withOutputStream {
      stream -> props.store(stream, null)
    }
}

}

(Apparently a) the Gradle Eclipse plugin doesn't know how to translate the compiler option -parameters to the .settings/org.eclipse.jdt.core.prefs setting org.eclipse.jdt.core.compiler.codegen.methodParameters=generate and b) there's no standard Gradle task that manipulates any of the property files in .settings, so you've got to roll your own.)

This is for Gradle 2.8.

like image 54
davidbak Avatar answered Oct 17 '22 19:10

davidbak


sourceCompatibility=1.8
[compileJava, compileTestJava]*.options*.compilerArgs = ['-parameters']
like image 24
patrikbeno Avatar answered Oct 17 '22 17:10

patrikbeno