Dynamically load content

I am trying to dynamically set the content of a panel based on a supplied class name. The fully qualified name of the class will be provided from a database that defines the UI. Below are the steps that I am trying to perform.

  1. Retrieve the name of the class from the database
  2. Load the class using the name from step 1
  3. Create an instance of the class
  4. Cast the class to a CustomComponent
  5. Set the content of the panel to the CustomComponet

I have tried to load the class using the code below:

package com.sms.session;

import com.sms.base.LoadErrorScreen;
import com.sms.lib.Container;

/**
 * @author flb
 *
 */
public class Loader {

    /**
     *
     */
    public Loader() {
        // TODO Auto-generated constructor stub
    }

    public static Container loadContainer (String className) {
        Container newContainer = null;
        try {
            Class newClass = Class.forName(className);
            
            if (newClass.isInstance(Container.class)) {
                newContainer = (Container) newClass.newInstance();
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        if (newContainer == null) {
            LoadErrorScreen le = new LoadErrorScreen();
            
            le.setClassName(className);
            
            newContainer = le;
        }
        
        return newContainer;
    }
}

But it returns a “java.lang.ClassNotFoundException”. From what I can tell at this point the issue might be that the class is in a “WAR” file on the Tomcat Server, so it is not finding it.

If anyone can provide some help and guidance, it would be appreciated.

Thank you

The example below worked when using full class names (com.example.MyCustomComponent)

public static CustomComponent loadContainer(String className) {
        CustomComponent newContainer = null;
        try {
            Class newClass = Class.forName(className);
            
            try {
                newContainer = (CustomComponent) newClass.newInstance();
            } catch (ClassCastException e) {
                e.printStackTrace();
            }
            
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        
        
        return newContainer;
    }

Thank you, that solved the problem. Any idea why the code I wrote did not work?
Thank you

Unfortunately, I don’t know why it did not work with your code… As far as I know, it should work that way too…