java.lang.Class类的getResource()方法用于获取具有此类指定资源的资源。该方法以URL对象的形式返回此类的指定资源。
用法:
public URL getResource(String resourceName)
参数:此方法接受参数resourceName,这是要获取的资源。
返回值:此方法以URL对象的形式返回此类的指定资源。
异常该方法抛出:
NullPointerException如果名称为null
下面的程序演示了getResource()方法。
范例1:
// Java program to demonstrate
// getResource() method
import java.util.*;
public class Test {
public int obj = 10;
public static void main(String[] args)
throws ClassNotFoundException
{
// returns the Class object for this class
Class myClass = Class.forName("Test");
System.out.println("Class represented by myClass:"
+ myClass.toString());
String resourceName = "obj";
// Get the resource of myClass
// using getResource() method
System.out.println(
resourceName + " resource of myClass:"
+ myClass.getResource(resourceName));
}
}
输出:
Class represented by myClass:class Test
obj resource of myClass:null
范例2:
// Java program to demonstrate
// getResource() method
import java.util.*;
class Main {
private Object obj;
public static void main(String[] args)
throws ClassNotFoundException, NoSuchFieldException
{
// returns the Class object for this class
Class myClass = Class.forName("Main");
System.out.println("Class represented by myClass:"
+ myClass.toString());
String resourceName = "obj";
try {
// Get the resource of myClass
// using getResource() method
System.out.println(
resourceName + " resource of myClass:"
+ myClass.getResource(resourceName));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
Class represented by myClass:class Main
obj resource of myClass:null