使用类Class时找不到类异常

时间:2014-08-16 12:22:23

标签: java classnotfound

Plz检查以下代码....类testError已经实例化但仍然生成了Class not found异常...如果这是真的那么为什么写在异常处理程序中的语句不会被打印?

class testError
{
  void display()
    {
      System.out.println("This is testError Class");
    }

}

class checkResult
{
  public static void main(String[] args)
     {
        testError te = new testError();
        te.display();// I hope the class has been created

        Class cls = Class.forName("testError"); // will throw ClassNotFound exception
                                                // Why??... Though the class has been 
                                                // instantiated

        // if we try to put it in trycatch block it will work...Why??

         try{ Class cls = Class.forName("testError");}

         catch(ClassNotFoundException e)
            {
              System.out.println("Error found");  //"Error found" will not be printed
                                                  // as the class has been instantiated
            }

      }
   }

2 个答案:

答案 0 :(得分:2)

我无法发表评论 - 因为我的声誉太低,但你的代码运行和调试很好 - 虽然我不得不改变它以使其编译:

    public static void main(String[] args) throws ClassNotFoundException {
    testError te = new testError();

    Class<?> cls = Class.forName("testError"); 
    try {
        cls = Class.forName("testError");
        // If you got there then everything went fine
        te.display();
    }
    catch (ClassNotFoundException e) {
        System.out.println("Error found"); 
    }
}

如何运行代码(从命令行,在IDE中)?什么是控制台输出? 如果您希望人们调查您的问题,您必须提供更多有用的信息。

最后,Java约定指定类名称应以大写字符( CheckResult TestError )开头。此外,您应该避免在默认包中使用类,因为这些类无法导入。

答案 1 :(得分:0)

首先遵循java命名约定

让您的主要课程公开

像mypackage一样创建一些包(不好在默认包中创建)并将类放在其中

并尝试以这种方式调用方法

String name = packageName.className.class.getName();//get the name of the class
className o = (className)Class.forName(name)
                               .newInstance();
//will give an instance of type Object so cast it
o.display();// call the method