You're on your way to the next level! Join the Kudos program to earn points and save your progress.
Level 1: Seed
25 / 150 points
Next: Root
1 badge earned
Challenges come and go, but your rewards stay with you. Do more to earn more!
What goes around comes around! Share the love by gifting kudos to your peers.
Keep earning points to reach the top of the leaderboard. It resets every quarter so you always have a chance!
Join now to unlock these features and more
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.
Hi @C_ Derek Fields,
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.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.