<Think in java >这本书的实例代码。
例子一、
package com.yuan.test;
//: typeinfo/SweetShop.java
//Examination of the way the class loader works.
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");
}
System.out.println("After Class.forName(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie");
}
}
//输出结果
inside main
Loading Candy
After creating Candy
Couldn’t find Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
//仔细研究了一下之后,对Class.forname(0的使用方法有了一些了解。例子一中没有找到Gum类的原因是,我在Class.forname("这里面没有指明类文件包文件名称+类名称")。我在例子二中给出了全名称之后就可以了。
例子二、
package com.yuan.test;
//: typeinfo/SweetShop.java
//Examination of the way the class loader works.
class Candy {
static {
System.out.println("Loading Candy");
}
}
class Gum {
static {
System.out.println("Loading Gum");
}
public void getA(){
System.out.println("调用我哦!");
}
}
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 c=Class.forName("com.yuan.test.Gum");
Object obj=null;
System.out.println("123:"+c.getName());
Gum gum=(Gum)c.newInstance();
gum.getA();
} catch (ClassNotFoundException e) {
System.out.println("Couldn’t find Gum");
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("After Class.forName(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie");
}
}
总结:Class.forname()实际上是获得类的申明。
Class c=Class.forName("com.yuan.test.Gum");
要想调用类的方法得这样做。使用 Class 的newinstance()方法来实例该类。
Object obj=null;
Gum gum=(Gum)c.newInstance();
gum.getA();