簡體   English   中英

如何使用velocity模板創建動態類時修復“class not found exception”

[英]How to fix “class not found exception” while creating dynamic class using velocity template

我使用速度模板創建了一個類的模板,並將動態變量傳遞給它。 它確實為我創建了一個類,但是當我嘗試加載該類時,它向我顯示“class not found exception”,因為類在類路徑中不存在。 有什么解決方案可以加載這個類嗎?

MainClass.vm //類的模板

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);
        }
}
}

您生成的是.java源文件。 Java需要.class編譯的文件。

所以,無論如何,您需要編譯生成的類。 如何做到這取決於您的環境,構建系統和您的需求。 它可以歸結為從構建腳本調用javac ,或以編程方式編譯然后加載類,如本問題中所述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM