etxalpo
etxalpo

Reputation: 1176

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:

Upvotes: 13

Views: 4230

Answers (3)

davidbak
davidbak

Reputation: 5999

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.

Upvotes: 2

patrikbeno
patrikbeno

Reputation: 1124

sourceCompatibility=1.8
[compileJava, compileTestJava]*.options*.compilerArgs = ['-parameters']

Upvotes: 1

xabufr
xabufr

Reputation: 21

After some research for the same problem, one solution is to make something like this: https://github.com/codeborne/mobileid/blob/master/build.gradle

Add this to your build.gradle:

[compileJava, compileTestJava]*.options.collect {options ->
    options.compilerArgs.add '-parameters'
}

It works for me with gradle 2.4

Upvotes: 0

Related Questions