getClassLoader().getResource() returns null

后端 未结 4 755
天命终不由人
天命终不由人 2020-11-28 13:08

I have this test app:

import java.applet.*;
import java.awt.*;
import java.net.URL;
public class Test extends Applet
{

    public void init()
    {
                 


        
4条回答
  •  余生分开走
    2020-11-28 13:35

    You don't need the slash at the start when getting a resource from a ClassLoader, because there's no idea of a "relative" part to start with. You only need it when you're getting a resource from a Class where relative paths go from the class's package level.

    In addition, you don't want Test.class.getClass() as that gets the class of Test.class, which will be Class.

    In other words, try either of these lines:

    URL viaClass=Test.class.getResource("/assets/pacman.png");
    URL viaLoader=Test.class.getClassLoader().getResource("assets/pacman.png");
    

提交回复
热议问题