菜鸟求指导 关于 thinking in java 中 forname 的问题
下面是thinking in Java 中的一段代码
package type_infomation;
class Candy
{
static
{
System.out.println("Loading Candy");
}
}
class Gum
{
static
{
System.out.println("Loading Gum");
}
}
class Cookie
{
static
{
System.out.println("Loading Cookie");
}
}
public class SweetShop
{
public static void main(String[] args)
{
System.out.println("inside main");
new Candy();
System.out.println("After creating Candy");
try
{
Class.forName("Gum");
}
catch (
ClassNotFoundException e)
{
System.out.println("Couldn't find Gum");
// TODO: handle exception
}
System.out.println("After Class.forname(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie");
}
}
关于forname:
It returns a Class reference, which is being ignored here; the call to
forName( ) is being made for its side effect, which is to load the class Gum if it isn’t already loaded. In the process of loading, Gum’s static clause is executed.
它说如果这个“Gum”类没有被装载的话,在调用forname的时候会一并加载。
所以运行的结果应该是:
//Output:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
但我把代码复制到eclipse自己再进行运行时会输出 Couldn't find Gum ,请问各位大大这是什么原因?
------解决方案--------------------嗯,package + 类名,唯一确定一个类。
------解决方案--------------------还有一个解决办法。
把“package type_infomation;”删掉就可以了。