简体   繁体   English

getClass和getResource的技术含义和使用

[英]Technical meaning and use of getClass and getResource

I m new in programming. 我是编程新手。 I watch online tutorials of Java and I came with this getClass().getResource() what is the technical use of these terms.Can anyone help me. 我看了Java的在线教程,并附带了这个getClass().getResource()这些术语的技术用途是什么。任何人都可以帮助我。

If you want to load some resource not using absolute/relate path of your file system, you should use the classloader. 如果要加载某些资源而不使用文件系统的绝对/相关路径,则应使用类加载器。 Your resource (for example icon.ico) can be packaged in foo.jar but some other icon with the same name can be also in bar.jar . 您的资源(例如icon.ico)可以被封装在foo.jar ,但具有相同名称的其他一些图标可以也bar.jar The getClass().getResource() statement helps to specify where the classloader will look for. getClass().getResource()语句有助于指定类加载器的查找位置。

getClass().getResource() will give you an URL to a file inside your jar. getClass()。getResource()将为您提供jar中文件的URL。 This is useful if your program depends of ie an datafile and you want to make sure it is always available. 如果您的程序依赖于数据文件,并且您想确保它始终可用,则此功能很有用。 getClass().getResourceAsStream() is the same concept only it returns a stream. getClass()。getResourceAsStream()是相同的概念,只是它返回一个流。

getClass() is defined in the Object class to return the "runtime class of this Object". 在Object类中定义了getClass()以返回“此Object的运行时类”。 where as getResource() "finds a resource with a given name". 其中,如getResource()“使用给定名称查找资源”。 for example if you pass getClass().getresource("sample.png") returned URL will be a File:// url for a sibling file with the name "sample.png". 例如,如果您传递getClass()。getresource(“ sample.png”),则返回的URL将是名称为“ sample.png”的同级文件的File:// URL。 In short it gives the absolute path of the file in your directory. 简而言之,它提供了目录中文件的绝对路径。

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

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