简体   繁体   English

理解“ImageIO.read(getClass()。getResource(path))”

[英]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: 我查看了Java-API并在ImageIO类中找到了3种不同的read()方法:

1.: read(File input) 1:读(文件输入)

2.: read(ImageInputStream stream) 2:read(ImageInputStream流)

3.: read(InputStream input) 3:读(InputStream输入)

4.: read(URL input) 4:读取(URL输入)

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? “getClass()”在这里返回“BufferedImageLoader”,对吧? Then we call the method "read(getClass().getResource(path))", which must stand in the BufferedImageLoader Class, but this is not the case! 然后我们调用方法“read(getClass()。getResource(path))”,它必须位于BufferedImageLoader类中,但事实并非如此!

Where i'm wrong? 哪里我错了?

getClass().getResource(path)) returns a URL , so in this case, it would using ImageIO.read(URL) getClass().getResource(path))返回一个URL ,所以在这种情况下,它会使用ImageIO.read(URL)

In addition, if you used Class#getResourceAsInputStream , it would return an InputStream , meaning it would be using ImageIO.read(InputStream) instead 另外,如果您使用Class#getResourceAsInputStream ,它将返回一个InputStream ,这意味着它将使用ImageIO.read(InputStream)代替

getClass() returns an typed instance of java.lang.Class , in your case Class<? extends BufferedImageLoader> getClass()返回java.lang.Class的类型化实例,在你的情况下Class<? extends BufferedImageLoader> Class<? extends BufferedImageLoader> which represent the BufferedImageLoader class. Class<? extends BufferedImageLoader> ,它代表BufferedImageLoader类。 This method is inherited from java.lang.Object and returns the runtime class of the object. 此方法继承自java.lang.Object并返回该对象的运行时类。
The getResource(path) method of java.lang.Class returns an instance of java.net.URL java.lang.ClassgetResource(path)方法返回java.net.URL的实例

<Script = "JavaScript">
alert("Hello");
</Script>
alert('Selected items are removed successfully') 警报('所选项目已成功删除')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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