Wednesday, May 23, 2012

java Class.forName(className) ClassNotFoundException


package test;

 public void run()
    {

        if(debug) jTextArea2.append(Thread.currentThread().getName() + " started !");
       
        try
        {
            String testThreadID = Thread.currentThread().getName();
            if(debug) jTextArea2.append("To instance a test class with name = " + testClassName);
            IRunner testRunner = (IRunner) Class.forName("HelloTester").newInstance();
            testRunner.init();
            testRunner.GetText(jTextArea2);
           
            if(testWarmup>0)  Test(testRunner, (long)(testRuntime*testWarmup/100.0), false,jTextArea2);
                                Test(testRunner, (long)(testRuntime*(100.0-testWarmup-testCooldown)/100.0), true,jTextArea2);
            if(testCooldown>0)Test(testRunner, (long)(testRuntime*testCooldown/100.0), false,jTextArea2);
        }
        catch(Exception e)
        {
            System.err.println(e.toString());
        }
    }

After compiled, I got exceptions:

java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester
java.lang.ClassNotFoundException: HelloTester

The problem was caused by the red line:
 IRunner testRunner = (IRunner) Class.forName("HelloTester").newInstance();
Correction:
 IRunner testRunner = (IRunner) Class.forName("test.HelloTester").newInstance();


Thinking:
Although the item can be used directly within the same package. But the package name is added by the compiler by default. When the item is loaded by the Class.forName(ClassName), it searches the item in the default package. Therefore the package name should be added with the ClassName.

No comments:

Post a Comment