Reputation: 57192
I am currently using
String myClass; // dynamically determined class name
Class.forName(myClass).newInstance()
to dynamically load objects in a spring app deployed to a tomcat server.
I've been reading (http://blog.bjhargrave.com/2007/09/classforname-caches-defined-class-in.html) that it a preferred approach to dynamically loading classes is using the ClassLoader.loadClass
, such as
ClassLoader.getSystemClassLoader().loadClass(myClass).newInstance()
In the second example, using loadClass
, I am getting an error that the class is not found. I suspect this is because I'm running within Tomcat the system class loader is not the class loader I actually want to be using.
When in a Tomcat app, which class loader should I be using if I want to use the loadClass mechanism?
Upvotes: 3
Views: 6411
Reputation: 3777
You can use getClassLoader().loadClass(myClass).newInstance()
,
It will look for the class in current classloader and will go to the parent classloader if not found.
myClass should be the fully qualified name like java.lang.String
Upvotes: 1
Reputation: 2020
Typically, you want to use the classloader that loaded your currently executing code. That is, you just want to call getClass().getClassLoader().loadClass(...)
. That said, there are times when you need to use a different class loader. When that is necessary requires hours and hours of training. So, you should always use the loader that loaded the currently executing code.
Upvotes: 2