class j {
public static void main(String args[])
{
Object obj=new Object();
String c ="Object";
System.out.println(Class.forName(c).isInstance(obj));
}
}在上面的代码中,我试图找出obj是否是对象的一个实例,我应该得到正确的答案,但是我得到了一个错误,我无法弄清楚为什么occurring.Can是错误的,请谁来帮我解决?
error: unreported exception ClassNotFoundException; must be caught or
declared to be thrown
System.out.println(Class.forName(c).isInstance(obj));发布于 2017-06-01 06:40:47
2件事:
Class.forName("Object")是不正确的,您需要使用所需类的完全限定名(即包含包)。来自javaDoc
参数:className -所需类的完全限定名。
String c = "java.lang.Object";
System.out.println(Class.forName(c).isInstance(obj));发布于 2017-06-01 06:39:54
您必须将代码包围在that中,或者必须确保main可以抛出excetpion:
try {
System.out.println(Class.forName(c).isInstance(obj));
} catch(ClassNotFoundException ex) {
// do something in case class can not be found
}或
public static void main(String args[]) throws ClassNotFoundException您不能离开代码,这是能够抛出异常,没有任何安全网。
确保使用类的完全限定名称:
java.lang.ClassNotFoundException 或者在源代码开始时导入它:
import java.lang.ClassNotFoundException;发布于 2017-06-01 06:49:21
方法Class.forName声明它抛出异常ClassNotFoundException,因此在您的代码中,您需要捕获它,或者在方法声明中声明抛出ClassNotFoundException。因此
Public static void main(String[] args) throws ClassNotFoundException {或
try {
System.out.println(Class.forName(c).isInstance(obj));
} catch (ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}https://stackoverflow.com/questions/44300141
复制相似问题