【问题标题】:NullPointerException when using a classLoader for loading an ImageIcon使用 classLoader 加载 ImageIcon 时出现 NullPointerException
【发布时间】:2015-05-18 09:44:05
【问题描述】:

为什么我在使用 ClassLoader 时会得到一个 nullPointerException

ClassLoader cl = ClassLoader.getSystemClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));

根据 Eclipse,NullPointerException 位于创建 imageIcon 的同一行

图像那里,因为以下工作正常:

 ImageIcon img = new ImageIcon("logo.png");

我正在使用类加载器,因为我想将它包含在一个可执行的 jar 中。

Eclipse 资源管理器中的项目。主函数在 Gui.java 中

【问题讨论】:

  • 你的项目结构是什么?
  • 你把logo,png图片放在哪里了?包含代码和 logo.png 的类文件是否在同一位置?
  • 在此语句之前添加一个空检查,例如 if(c1!=null) ImageIcon img = new ImageIcon(cl.getResource("logo.png"));
  • @DeviKiran - 是的 - 通过不使用 ClassLoader 来证明(我的问题)
  • @npinti - 我不确定我是否正确 - 但我上传了一张图片并添加了一些文字

标签: java classloader executable-jar imageicon


【解决方案1】:
ClassLoader cl = ClassLoader.getSystemClassLoader();

clnull,因为你从引导类加载器调用它,根据java's api

getClassLoader

public ClassLoader getClassLoader()

某些实现可能使用 null 来表示引导类加载器。此方法将返回 null 在此类实现中,如果此类由引导程序加载 类加载器。

由于cl 为空,这就是您的代码在使用时抛出NullPointerException 的原因。

【讨论】:

  • 可能会或可能不会 - OP 没有准确说明 NPE 发生的位置。但更有可能的是,SystemClassloader 没有找到所请求的资源
  • OP 使用的是getSystemClassLoader() 而不是getClassLoader()。在 bootstrap 类加载器的情况下也可能返回 null。因此,String.class.getClassLoader() 将返回 nullClassLoader.getSystemClassLoader() 不应返回 null。 @java在创建图像之前检查cl之前classloader的值是什么
【解决方案2】:

按照下面的方法做

ClassLoader cl = this.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("logo.png"));

【讨论】:

  • @java 我认为上述解决方案在静态方法中不起作用,最好使用非静态并尝试....它会起作用
【解决方案3】:

这可能是一个有点脏的解决方案 - 但我尝试将图像放在 bin 文件夹中,然后它就可以正常工作了!!!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    • 2013-08-08
    • 2018-09-05
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2013-08-17
    相关资源
    最近更新 更多