velocitydynamic-class-loadersliferay-velocity

How to fix "class not found exception" while creating dynamic class using velocity template


I have created a template of a class using velocity template and passed dynamic variables to it. It did created a class for me but when i tried to load that class it showed me "class not found exception" as the class is not present in class path. Is there any solution through which i can load this class?

MainClass.vm //template of class

public class $className
{
public static void main (String[] args ){

  System.out.println("Hello $name");
}

}

HelloWorld.java
public class HelloWorld {

    public static void main(String[] args) {
        String className = "MainClass";
        try{
         /*  first, get and initialize an engine  */
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        /*  next, get the Template  */
        Template t = ve.getTemplate( "MainClass.vm" );
        /*  create a context and add data */
        VelocityContext context = new VelocityContext();
        context.put("className", className);
        context.put("name", "World");
        /* now render the template into a StringWriter */
        FileWriter fileWriter = new FileWriter(className + ".java");
        t.merge(context, fileWriter);
        Class.forName("MainClass");
        fileWriter.flush();
    }
        catch(Exception exception)
        {
            System.err.println(exception);
        }
}
}

Solution

  • What you generate is a .java source file. Java needs .class compiled files.

    So one way or another, you will need to have your generated class compiled. And how to do it depends on your environment, your build system and your needs. It can boils down to invoking javac from your build scripts, or to programmatically compile then load the class, as detailed in this question.