简体   繁体   中英

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

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?

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

getClass() returns an typed instance of java.lang.Class , in your case Class<? extends BufferedImageLoader> 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM