I'm running Eclipse Java-EE with Tomcat and I'm trying to figure out how to load a class but so far have had no luck. Since I'm running Tomcat will the classes be loaded based on Tomcat's directory where it compiles the java folders to class files?
An example is:
ClassLoader myClassLoader = DataType.class.getClassLoader();
DataType load(String classname)
{
try{
String class1name = classname;
Class myClass = myClassLoader.loadClass(class1name);
Constructor maker = myClass.getConstructor();
DataType datatype = (DataType) maker.newInstance();
开发者_StackOverflow return datatype;
} catch(Exception ex)
{
return null;
}
}
What I'm passing is a simple name say "classname" do I need to specify more then just the name of the file?
A full class name consists of the package and the class names, like "java.lang.String".
It's a almost always a good idea to print an exception that you catch. Otherwise, when something goes wrong, you won't know why.
The variable
class1name
is redundant. You can just doloadClass(classname)
.Class loading in a servlet container like Tomcat is a little more complicated than in a regular application. There's the root class loader, plus a separate loader for each application (which has the root loader as its parent). Most of the time, you don't need to know about any of this, but it becomes significant when you're loading resources from the classpath, or loading classes dynamically. Which brings us to the most important question:
Why are you even using dynamic class loading? There might be a good reason, but it's not clear from the provided code.
Have you tried myClassLoader.loadClass(class1Name, true)
see here ?
I was wondering if you can simply do this:
Class myClass = Class1Name.class;
Obviously,you will have to import the class. Just a suggestion if you do not want to load class dynamically.
精彩评论