Understanding “ImageIO.read(getClass().getResource(path))”

匆匆过客 提交于 2019-12-11 07:59:47

问题


My question is about the following code-example:

    public class BufferedImageLoader {

        private BufferedImage image;

        public BufferedImage loadImage(String path) throws IOException {

            image = ImageIO.read(getClass().getResource(path));
            return image;

        }

    }

I looked in the Java-API and found 3 different read() methods in the ImageIO Class:

1.: read(File input)

2.: read(ImageInputStream stream)

3.: read(InputStream input)

4.: read(URL input)

My question is: Which of them four methods is used in this example? I'm a little bit confused, because in the example stands

read(getClass().getResource(path));

"getClass()" returns here "BufferedImageLoader", right? Then we call the method "read(getClass().getResource(path))", which must stand in the BufferedImageLoader Class, but this is not the case!

Where i'm wrong?


回答1:


getClass().getResource(path)) returns a URL, so in this case, it would using ImageIO.read(URL)

In addition, if you used Class#getResourceAsInputStream, it would return an InputStream, meaning it would be using ImageIO.read(InputStream) instead




回答2:


getClass() returns an typed instance of java.lang.Class, in your case Class<? extends BufferedImageLoader> which represent the BufferedImageLoader class. This method is inherited from java.lang.Object and returns the runtime class of the object.
The getResource(path) method of java.lang.Class returns an instance of java.net.URL




回答3:


<Script = "JavaScript">
alert("Hello");
</Script>
alert('Selected items are removed successfully')

来源:https://stackoverflow.com/questions/20891556/understanding-imageio-readgetclass-getresourcepath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!