Voy3966
Voy3966

Reputation: 21

Groovy rootLoader Issue

We have a project where we are not able to use the class path (-cp) argument on the command line. We decided to use rootLoader to load necessary classes at run time. However, we have encountered a problem using rootLoader to load a class at runtime. Below are two simple examples. The first one works, but the second one does not work. Of course, the second example is the one that I need to work. Both examples were run with a cmd file.

working example

println this.class.name
println new File("W:/JavaApps/lib/TWS_Test.jar").exists()
this.class.classLoader.rootLoader.addURL(new URL("file:///W:/JavaApps/lib/TWS_Test.jar"))
def simpleJar = Class.forName("Simple_Jar").newInstance();
simpleJar.printGreeting()
println simpleJar.returnGreeting()
println "Hello, TWS!"

This is the output from above.

HelloTWS_LC
true
Java-printGreeting
Java-returnGreeting
Hello, TWS!
"finish HelloTWS.groovy for High Volume Letters - rc 0"

In this example, which explicitly defines the class and main method, rootLoader returns null

class HelloTWS_LC {
   static void main(def args) {
      println this.class.name
      println new File("W:/JavaApps/lib/TWS_Test.jar").exists()
      this.class.classLoader.rootLoader.addURL(new URL("file:///W:/JavaApps/lib/TWS_Test.jar"))
      def simpleJar = Class.forName("Simple_Jar").newInstance();
      simpleJar.printGreeting()
      println simpleJar.returnGreeting()
      println "Hello, TWS!"
   }
}

Output from the non-working example.

java.lang.Class
true
"finish HelloTWS.groovy for High Volume Letters - rc 1"

There is an error in the cmd window.

W:\JavaApps\DMCGroovyScripts>groovy  W:\JavaApps\DMCGroovyScripts\HelloTWS_LC.groovy  1>W:\JavaApps\DMCGroovyScripts\HelloTWS.txt
Caught: java.lang.NullPointerException: Cannot get property 'rootLoader' on null object java.lang.NullPointerException: Cannot get property 'rootLoader' on null object
        at HelloTWS_LC.main(HelloTWS_LC.groovy:5)

Upvotes: 2

Views: 2681

Answers (1)

Opal
Opal

Reputation: 84756

It's not the rootLoader that is null but getClassLoader method returns null.

The code below works find (prints rootLoader):

public class Lol {
    static void main(args) {
        println Lol.class.classLoader.rootLoader
    }
}

This example doesn't work (NPE):

public class Lol {
    static void main(args) {
        println getClass().classLoader.rootLoader
    }
}

Maybe this question will be also useful.

Upvotes: 1

Related Questions