What is the difference between Class.getResource() and ClassLoader.getResource()?

前端 未结 7 1886
情歌与酒
情歌与酒 2020-11-22 02:25

I wonder what the difference is between Class.getResource() and ClassLoader.getResource()?

edit: I especially want to know if any cachi

7条回答
  •  失恋的感觉
    2020-11-22 03:24

    Class.getResource can take a "relative" resource name, which is treated relative to the class's package. Alternatively you can specify an "absolute" resource name by using a leading slash. Classloader resource paths are always deemed to be absolute.

    So the following are basically equivalent:

    foo.bar.Baz.class.getResource("xyz.txt");
    foo.bar.Baz.class.getClassLoader().getResource("foo/bar/xyz.txt");
    

    And so are these (but they're different from the above):

    foo.bar.Baz.class.getResource("/data/xyz.txt");
    foo.bar.Baz.class.getClassLoader().getResource("data/xyz.txt");
    

提交回复
热议问题