Nick
Nick

Reputation: 45

Loading groovy class with dependencies

Say I wanted to use GroovyClassLoader to load a class that uses several other classes

test1.groovy  
|  
|_test2.groovy
|            |
|            test3.groovy
|
test4.groovy

Other than loading them in order test4->test3->test2->test1. Could I just load test1 and have all of its dependencies loaded with it?

Upvotes: 2

Views: 938

Answers (1)

tim_yates
tim_yates

Reputation: 171054

Given File1.groovy like:

import File2

new File2().sayHi( 'tim' )

And File2.groovy like:

class File2 {
    def sayHi( name ) {
        println "Hi $name"
    }
}

And Test.java like:

import groovy.lang.GroovyClassLoader ;
import groovy.lang.GroovyObject ;

public class Test {
    public static void main( String[] args ) throws Exception {
        GroovyClassLoader loader = new GroovyClassLoader() ;
        GroovyObject o = (GroovyObject)loader.loadClass( "File1" ).newInstance() ;
        o.invokeMethod( "run", new Object[] {} ) ;
        loader.close() ;
    }
}

I can compile it with:

javac -cp groovy-all-2.2.1.jar:. Test.java 

And when I do:

java -cp groovy-all-2.2.1.jar:. Test

It prints:

Hi tim

How is my example different to what you have, and can you add the difference in to your question?

Upvotes: 1

Related Questions