0

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

gnsandeep
  • 25
  • 5

2 Answers2

0

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);
Kiran Bhagwat
  • 574
  • 1
  • 6
  • 13
0
System.out.println(cls.getDeclaredMethod( "doIt", new Class[] {}).invoke( obj,  new Object[] {} ));
gnsandeep
  • 25
  • 5