简体   繁体   中英

Loading classes

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();           
          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?

  1. A full class name consists of the package and the class names, like "java.lang.String".

  2. 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.

  3. The variable class1name is redundant. You can just do loadClass(classname) .

  4. 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:

  5. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM