Kyle
Kyle

Reputation: 22035

Is there any way to use groovy and java code for the same class?

I mainly program in groovy, but occasionally it's too slow. So I write a separate .java class, and put the code that needs to run faster in a java method and call that java method from my groovy code.

This causes me to end up with two separate files and two separate classes. Is there any way I could embed a java method right into the groovy file, maybe marking it with an annotation to indicate that it is java?

Upvotes: 1

Views: 317

Answers (2)

Angel O'Sphere
Angel O'Sphere

Reputation: 2666

You don't need to do anything special.

Just write the Java class behind the groovy class. 99% of all Java source is valid groovy source as well.

class GroovyClass {
    def a;
    def doSomething(x,y) { return x*y; }
}
class JavaClass {
    SomeType someVar;
    public JavaClass() { /* ... */ } // some contructor
    public void doit(String a, int b) {} // full typed method, that is java
}

Groovy++ is somethign completely different. The JavaClass needs to have everything fully typed to be "Java" however your problem can be solved far easyer if you just use types in the relevant groovy methods.

class AnotherGroovyClass {
   // typed
   public Result someMethod(SomeArg arg1, SomeOtherArg arg2) {
   }
   def someVariable; // untyped
}

If you think the lack of speed comes from the dynamic nature of groovy then just use full types at the relevant points.

Upvotes: 0

ataylor
ataylor

Reputation: 66059

This is the idea behind groovy++. Marking a class or method with the @Typed annotation will cause it to use static typing instead of dynamic typing, while still retaining a lot of goodness of groovy.

While not exactly java, typed groovy++ methods generally perform about the same as java would.

More information on groovy++ is available at: https://code.google.com/p/groovypptest/wiki/Welcome

Upvotes: 2

Related Questions