[讨论] 分享velocity中Class.forName("") 报ClassNotFoundException的问题

lvjun106 2012-04-25
近日在做velocity自定义指令时,经常碰到ClassNotFoundException.
查看源代码,


private void loadDirective(String directiveClass, String caption)
    {
        try
        {
            Object o = Class.forName(directiveClass).newInstance();
            if(o instanceof Directive)
            {
                Directive directive = (Directive)o;
                runtimeDirectives.put(directive.getName(), directive);
                info((new StringBuilder("Loaded ")).append(caption).append(" Directive: ").append(directiveClass).toString());
            } else
            {
                error((new StringBuilder(String.valueOf(caption))).append(" Directive ").append(directiveClass).append(" is not org.apache.velocity.runtime.directive.Directive.").append(" Ignoring. ").toString());
            }
        }
        catch(Exception e)
        {
            error((new StringBuilder("Exception Loading ")).append(caption).append(" Directive: ").append(directiveClass).append(" : ").append(e).toString());
        }
    }


原来VELOCITY在加载自定义指令时用的是Class.forName,生成新对象,
杯具的是我自定义的class是与velocity.jar不在同一个项目中,更不在同一级目录中,而Class.forName,如果这么写的话,是默认用dependClass的类加载器,即本身类加载器,所以才会报出ClassNotFoundException.

解决方案其实只要把类加载器换成当前线程的即可。
Thread.currentThread().getContextClassLoader()

在此想问问各位大神,JVM在调用一个JAR时是怎样生成一个classLoader的?
Global site tag (gtag.js) - Google Analytics