【问题标题】:Play: ClassLoader cannot find my class播放:ClassLoader 找不到我的班级
【发布时间】:2016-06-01 03:31:18
【问题描述】:

我正在使用 Play for Java,并在我的 Application.java 中进行了尝试

    // The name of the class to search
    String className = "my.fake.company.SuperGreatClass";
    Reflections reflections = new Reflections("", new SubTypesScanner(false));

    // All classes
    Set<Class<? extends Object>> allClasses = reflections.getSubTypesOf(Object.class);

    for (Class c : allClasses){
        String cName = c.getName();
        // Find the class that matches the name to the one we are looking for
        if (cName.contains(className))
            play.Logger.info(cName); // It always succeeds and logs the name correctly
    }

    ClassLoader classLoader = ClassLoader.getSystemClassLoader();

    try {
        Class clazz = classLoader.loadClass(className);
        Constructor constructor = clazz.getConstructor();
    } catch (Exception e) {
        play.Logger.error("NOT FOUND: " + e.getMessage());
        return badRequest("Cannot find that super great class of yours!");
    }

反射部分正确识别我的类,但 ClassLoader 没有。不幸的是,我使用了使用第二种方法的第三方库,我无法更改它。

我可以做些什么来改变 ClassLoader 的行为吗?我找到了这个answer,但我不确定这是否可行。

日志输出为:

2016-02-19 16:00:17 +0200 [INFO ] from application in application-akka.actor.default-dispatcher-3 -  - my.fake.company.SuperGreatClass
2016-02-19 16:00:18 +0200 [ERROR] from application in application-akka.actor.default-dispatcher-3 -  - NOT FOUND: my.fake.company.SuperGreatClass

【问题讨论】:

    标签: java playframework playframework-2.0 java-8


    【解决方案1】:

    请阅读 Java 中的类加载器层次结构及其遵循的合同。 This article is one of many describing the loaders hierarchy

    在您的代码中,您要求 System Classloader 加载您的类。这意味着它只会为您的类查询 BootstrapSystem 类加载器。

    要增加搜索区域,只需调用

    this.getClass().getClassLoader().loadClass(className); 
    

    ... 这应该返回您的课程。

    【讨论】:

    • 是的,我应该指定它。在“classLoader.loadClass”命令中抛出异常,这是一个找不到类的异常。
    • 感谢您的澄清!我正在编辑答案,因为我错过了一些明显的东西。
    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2013-09-17
    相关资源
    最近更新 更多