18

我正在开发一个监视目录并在看到目录中的更改时运行目录中的所有测试的程序。

这要求程序动态加载类,而不是获取缓存的副本。

我可以动态加载测试类。对测试的更改在运行时被检测和使用。但是,测试所测试的类并非如此。

我用于动态加载类并返回测试类列表的代码:

List<Class<?>> classes = new ArrayList<Class<?>>();
    for (File file : classFiles) {
        String fullName = file.getPath();
        String name = fullName.substring(fullName.indexOf("bin")+4)
                .replace('/', '.')
                .replace('\\', '.'); 
        name = name.substring(0, name.length() - 6);

            tempClass = new DynamicClassLoader(Thread.currentThread().getContextClassLoader()).findClass(name)          } catch (ClassNotFoundException e1) {
            // TODO Decide how to handle exception
            e1.printStackTrace();
        }

        boolean cHasTestMethods = false;
        for(Method method: tempClass.getMethods()){
            if(method.isAnnotationPresent(Test.class)){
                cHasTestMethods = true;
                break;
            }
        }
        if (!Modifier.isAbstract(cachedClass.getModifiers()) && cHasTestMethods) {
            classes.add(tempClass);
        }
    }
    return classes;

使用 DynamicClassLoader 作为此处描述的 Reloader如何强制 Java 在实例化时重新加载类?

知道如何解决吗?我认为所有类都会被动态加载。但是请注意,我不会在我的 DynamicClassLoader 中覆盖 loadclass,因为如果我这样做,我的测试类会给出 init

编辑:这不起作用,类被加载但未检测到其中的测试......

List<Request> requests = new ArrayList<Request>();
    for (File file : classFiles) {
        String fullName = file.getPath();
        String name = fullName.substring(fullName.indexOf("bin")+4)
                .replace('/', '.')
                .replace('\\', '.'); 
        name = name.substring(0, name.length() - 6);
        Class<?> cachedClass = null;
        Class<?> dynamicClass = null;
        try {
            cachedClass = Class.forName(name);


            URL[] urls={ cachedClass.getProtectionDomain().getCodeSource().getLocation() };
            ClassLoader delegateParent = cachedClass .getClassLoader().getParent();
            URLClassLoader cl = new URLClassLoader(urls, delegateParent) ;
            dynamicClass = cl.loadClass(name);
            System.out.println(dynamicClass);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

编辑编辑:我检测这样的测试方法:

            for(Method method: dynamicClass.getMethods()){
            if(method.isAnnotationPresent(Test.class)){
                requests.add(Request.method(dynamicClass, method.getName()));
            }
        }
4

1 回答 1

14

如果您使用的自定义ClassLoader与链接答案中的完全一样,则它不会覆盖该方法protected Class<?> loadClass(String name, boolean resolve)。这意味着当 JVM 解决依赖关系时,它仍然会委托给父类加载器。而且,当然,当它不委托给父母ClassLoader时,它有可能错过一些必需的课程。

最简单的解决方案是设置正确的父类加载器。您当前正在传递Thread.currentThread().getContextClassLoader()这有点奇怪,因为您的主要意图是委托不应委托给该加载器,而是加载更改的类。您必须考虑存在哪些类加载器以及使用哪些类加载器以及不使用哪些类加载器。例如,如果该类Foo在您当前代码的范围内,但您想使用新的 ClassLoader (重新)加载它,Foo.class.getClassLoader().getParent()那么它将是新的正确委托父级ClassLoader。请注意,可能是null这样,但这并不重要,因为在这种情况下,它将使用引导加载程序,该引导加载程序是正确的父项。

请注意,当您设置ClassLoader符合您意图的正确父级时,您不再需要该自定义ClassLoader。默认实现(参见 参考资料URLClassLoader)已经做了正确的事情。并且在当前的 Java 版本中,Closeable它更适合动态加载场景。

这是一个类重新加载的简单示例:

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;

public class ReloadMyClass
{
  public static void main(String[] args)
  throws ClassNotFoundException, IOException {
    Class<?> myClass=ReloadMyClass.class;
    System.out.printf("my class is Class@%x%n", myClass.hashCode());
    System.out.println("reloading");
    URL[] urls={ myClass.getProtectionDomain().getCodeSource().getLocation() };
    ClassLoader delegateParent = myClass.getClassLoader().getParent();
    try(URLClassLoader cl=new URLClassLoader(urls, delegateParent)) {
      Class<?> reloaded=cl.loadClass(myClass.getName());
      System.out.printf("reloaded my class: Class@%x%n", reloaded.hashCode());
      System.out.println("Different classes: "+(myClass!=reloaded));
    }
  }
}
于 2013-11-20T11:20:34.473 回答