Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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

<Script = "JavaScript">
alert("Hello");
</Script>
alert('Selected items are removed successfully')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top