Java中的类 forName() 方法及示例
Java.lang.Class 类的forName()方法用于获取具有指定类名的这个Class 的实例。此类名称被指定为字符串参数。
句法:
public static Class forName(String className) throws ClassNotFoundException
参数:此方法接受参数className ,即需要其实例的 Class。
返回值:该方法返回具有指定类名的该类的实例。
异常:此方法抛出以下异常:
- LinkageError:如果链接失败
- ExceptionInInitializerError:如果此方法引发的初始化失败
- ClassNotFoundException:如果找不到该类
下面的程序演示了 forName() 方法。
示例 1:
Java
// Java program to demonstrate forName() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// get the Class instance using forName method
Class c1 = Class.forName("java.lang.String");
System.out.print("Class represented by c1: "
+ c1.toString());
}
}
Java
// Java program to demonstrate forName() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// get the Class instance using forName method
Class c1 = Class.forName("java.lang.Integer");
System.out.print("Class represented by c1: "
+ c1.toString());
}
}
输出:
Class represented by c1: class java.lang.String
示例 2:
Java
// Java program to demonstrate forName() method
public class Test {
public static void main(String[] args)
throws ClassNotFoundException
{
// get the Class instance using forName method
Class c1 = Class.forName("java.lang.Integer");
System.out.print("Class represented by c1: "
+ c1.toString());
}
}
输出:
Class represented by c1: class java.lang.Integer
参考: https://docs.oracle.com/javase/9/docs/api/ Java/lang/Class.html#forName-java.lang.String-