I have a script structure that might look like this:
scripts/
my_main_class.groovy
my_class/
my_class1.groovy
my_class2.groovy
From "my_main_class", I want to instantiate either "my_class1" or "my_class2" depending on a variable.
I am trying use the following:
def cname = 'my_class1'
def a = this.getClass().classLoader.loadClass(cname)?.newInstance()
I get a java.lang.ClassNotFoundException: my_class1 error.
Clearly the CLASS_PATH is not finding this class. Does anyone know how to make this work?
I can instantiate the classes normally
import my_class.my_class1
def a = new my_class1()
Thanks to @Ram Kumar Aravindakshan _Adaptavist_ I relooked at my code and I found that by specifying the complete path, the classloader worked. The corrected code is
def cname = 'my_class.my_class1'
def a = this.getClass().classLoader.loadClass(cname)?.newInstance()
This successfully loads the class.
Your import statement is incorrect.
When importing a class, you should only do:-
import my_class.my_class1
You must not add the file extension to the import statement. It should only contain the package name followed by the class name.
Please give it a try and let me know how it goes.
Thank you and Kind regards,
Ram
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Thanks - that was a typo when I was creating the sample. My code imports the class correctly. I don't think it has to do with the import statement. I think it has to do with the CLASS_PATH not covering subdirectories.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
In my experience you can have problems instantiating classes like this.
if you run this immediately after clear cache the classes won't be compiled
I've also seen issues where expected super class doesn't match super class of instantiated object.
Can I ask, why do you want to do this ?
I started investigating this approach because factories classes caused a big chain of compilation, which caused other problems
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Online forums and learning are now in one easy-to-use experience.
By continuing, you accept the updated Community Terms of Use and acknowledge the Privacy Policy. Your public name, photo, and achievements may be publicly visible and available in search engines.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.