Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Groovy compiler apparently produce 1.5 version of Java?

After some problems with differences between JSE versions, I'm trying to log the Java compiler version used to compile (it's Groovy 2.1.9, Grails 2.3.8, Java 1.7.0_60 in fact).

After some rummaging around, I've constructed this piece of code to read the leading bytes of the class - see /http://en.wikipedia.org/wiki/Java_class_file#General_layout

(change the path to the class to match the package name):

class CompilerVersionSupport {

  public static String getVersion() {
    String classAsPath = 'com/my/organisation/CompilerVersionSupport.class';
    InputStream stream = (new CompilerVersionSupport()).getClass().getClassLoader().getResourceAsStream(classAsPath);
    DataInputStream ins = new DataInputStream (stream)

    assert( ins.readUnsignedShort() == 0xcafe )    
    assert( ins.readUnsignedShort() == 0xbabe )
    int minor = ins.readUnsignedShort();
    int major = ins.readUnsignedShort();
    ins.close();
    int javaVersion = major - 44 
    return "1.$javaVersion"
    }     
}

Trouble is, it returns 1.5.

What could be going on?

  • Charles
like image 677
CharlesW Avatar asked Jul 15 '14 11:07

CharlesW


People also ask

Is Groovy compiled to Java?

Groovy scripts can use any Java classes. They can be compiled to Java bytecode (in . class files) that can be invoked from normal Java classes. The Groovy compiler, groovyc, compiles both Groovy scripts and Java source files, however some Java syntax (such as nested classes) is not supported yet.

Is Groovy compatible with Java?

Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk.

Does Java 11 use Groovy?

Getting started with Groovy and Java 11 project Since JDK 11 requirements have changed for Groovy, you need to perform some additional steps to successfully run the Groovy code in IntelliJ IDEA. In this tutorial, you'll create a Groovy project with JDK 11, add simple code, and run a Groovy script.


1 Answers

The default Groovy behaviour is not to compile the code with the same bytecode version as the JDK being used. 1.5 is the default for compatibility reasons, IMHO. If you want the compiler to output newer bytecode you need to set that explicitly.

For example if you're using Maven to compile the code, you can use the GMavenPlus plugin. See the description of the targetBytecode parameter.

If you're not using Maven you can use -Dgroovy.target.bytecode=1.7 or research the possibilities for your particular build tool

like image 108
Daniel Kvasnicka Avatar answered Sep 24 '22 16:09

Daniel Kvasnicka