Java : GroovyClassLoader : cannot find symbol for method in Groovy Class

259 Views Asked by At

I am trying to use GroovyClassLoader in java to execute a method in Groovy Class.

I have created a Java Class, pubic method which creates a instance of GroovyClassLoader , parseClass and then creates a new Instance of the class, Calls a method in the class.


public class Gtest{

   public static void main(String args[])throws IOException , InstantiationException ,IllegalAccessException {

       GroovyClassLoader gcl = new GroovyClassLoader();       

       Class cls =  gcl.parseClass("class Foo { void doIt() { println \"ok\" } }");
       Object obj = cls.newInstance();
       if(obj == null){
           System.out.println("null");
       }
       obj.doIt();


   }
}

Error : Gtest.java:22: error: cannot find symbol obj.doIt(); ^ symbol: method doIt() location: variable obj of type Object 1 error

2

There are 2 best solutions below

0
On BEST ANSWER

Its because object class doesn't have doIt() method. You have to use below syntax to invoke your method.

Method sumInstanceMethod
  = Operations.class.getMethod("doIt");
 Object result
      =  sumInstanceMethod.invoke(obj, null);
0
On
System.out.println(cls.getDeclaredMethod( "doIt", new Class[] {}).invoke( obj,  new Object[] {} ));