I’m trying to import a class defined in a different groovy file using evaluate
method, please view the snippet or the contents of the file(s) which defines the class and tries to use evaluate
method to execute the class as follows
// File: sample.groovy
class Person {
String firstName
String lastName
String getFullName() {
return "$firstName $lastName"
}
def addMarksInSubjects(a, b){
return a+b;
}
}
I’m calling Person class in a different groovy file under Main class as follows
// runfile.groovy
// Load the Person class from sample.groovy
evaluate(new File('sample.groovy'))
class Main {
static void main(String[] args) {
// Create an instance of Person
def person = new Person(firstName: 'Stack', lastName: 'Overflow')
// Use the method from the Person class
println "Full Name: ${person.getFullName()}"
}
}
the folder structure is simple
.
├── runcode.groovy
└── sample.groovy
During compilation I’m encountering the following error which suggests my usage is not applicable for static void main(String[] args)
and sadly I’m not sure as to how to proceed further.
Caught: groovy.lang.MissingMethodException: No signature of method: static Person.main() is applicable for argument types: ([Ljava.lang.String;) values: [[]]
Possible solutions: wait(), wait(long), any(), find(), wait(long, int), any(groovy.lang.Closure)
groovy.lang.MissingMethodException: No signature of method: static Person.main() is applicable for argument types: ([Ljava.lang.String;) values: [[]]
Possible solutions: wait(), wait(long), any(), find(), wait(long, int), any(groovy.lang.Closure)
Please Note:
- The reason for using
evaluate
method in my approach is based on logical inference thatevaluate
method could dynamically execute the script stored in a file in the current context. Please let me know of any suitable resolution which would be helpful - Some baseline research led me to the following answer here , sadly it is entirely not clear.
1
evaluate
is a wrapper around return script.run()
. Running a class
requires it to have a main
method, which you don’t have, thus the error. In your example it would make more sense to use parseClass()
:
def clazz = new GroovyClassLoader().parseClass(new File('sample.groovy'))
println clazz.newInstance()
It might or might not be what you want, but based on your example this is how you can get it to work.