Java程序思考如下:
package typeinfo;
import static util.Print.*;
class Candy {
static { print("Loading Candy"); }
}
class Gum {
static { print("Loading Gum"); }
}
class Cookie {
static { print("Loading Cookie"); }
}
public class SweetShop {
public static void main(String[] args) {
print("inside main");
new Candy();
print("After creating Candy");
try {
Class.forName("Gum");
} catch(ClassNotFoundException e) {
print("Couldn't find Gum");
}
print("After Class.forName(\"Gum\")");
new Cookie();
print("After creating Cookie");
}
}
我期待输出如下:
/* Output:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
*/
但是得到
inside main
Loading Candy
After creating Candy
Couldn't find Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
显然,try块抛出了一个ClassNotFoundException,这是意料之外的。任何想法为什么代码抛出这个而不是按预期初始化Gum类?
答案 0 :(得分:53)
您的课程位于typeinfo
个包中,因此他们的完全限定名称为typeinfo.Gum
,typeinfo.Candy
和typeinfo.Cookie
。 Class.forName()
只接受完全限定名称:
<强>参数:强>
className
- 所需类的完全限定名称。
将您的代码更改为:
try {
Class.forName("typeinfo.Gum");
} catch(ClassNotFoundException e) {
print("Couldn't find Gum");
}