Posted on 2008-11-19 10:35
非洲小白臉 閱讀(141)
評(píng)論(0) 編輯 收藏
下面我以顧客買(mǎi)相機(jī)為例來(lái)說(shuō)明Java反射機(jī)制的應(yīng)用。例子中涉及的類(lèi)和接口有:
Camera接口:定義了takePhoto()方法。
Camera01類(lèi):一種照相機(jī)的類(lèi)型,實(shí)現(xiàn)Camera接口。
Camera02類(lèi):另一種照相機(jī)的類(lèi)型,實(shí)現(xiàn)Camera接口。
Seller類(lèi):賣(mài)照相機(jī)。
Customer類(lèi):買(mǎi)相機(jī),有main方法。
所有類(lèi)都放在com包里
程序如下:
public interface Camera {
//聲明照相機(jī)必須可以拍照
public void takePhoto();
}
public class Camera01 implements Camera {
private final int prefixs =300;//300萬(wàn)象素
private final double optionZoom=3.5; //3.5倍變焦
public void takePhoto() {
System.out.println("Camera01 has taken a photo");
}
}
類(lèi)似的有
public class Camera02 implements Camera {
private final int prefixs =400;
private final double optionZoom=5;
public void takePhoto() {
System.out.println("Camera02 has taken a photo");
}
}
顧客出場(chǎng)了
public class Customer {
public static void main(String[] args){
//找到一個(gè)售貨員
Seller seller = new Seller();
//向售貨員詢(xún)問(wèn)兩種相機(jī)的信息
seller.getDescription("com.Camera01");
seller.getDescription("com.Camera02");
//覺(jué)得Camera02比較好,叫售貨員拿來(lái)看
Camera camera =(Camera)seller.getCamera("com.Camera02");
//讓售貨員拍張照試一下
seller.testFuction(camera, "takePhoto");
}
}
Seller類(lèi)通過(guò)Java反射機(jī)制實(shí)現(xiàn)
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Seller {
//向顧客描述商品信息
public void getDescription(String type){
try {
Class cla = Class.forName(type);
//生成一個(gè)實(shí)例對(duì)象,在編譯時(shí)我們并不知道obj是什么類(lèi)型。
Object obj = cla.newInstance();
//獲得type類(lèi)型所有已定義類(lèi)變量及方法。
Field[] fileds = cla.getDeclaredFields();
Method[]methods = cla.getDeclaredMethods();
System.out.println("The arguments of this Camera is:");
for(int i=0;i<fileds.length;i++){
fileds[i].setAccessible(true);
//輸出類(lèi)變量的定義及obj實(shí)例中對(duì)應(yīng)的值
System.out.println(fileds[i]+":"+fileds[i].get(obj));
}
System.out.println("The function of this Camera:");
for(int i=0;i<methods.length;i++){
//輸出類(lèi)中方法的定義
System.out.println(methods[i]);
}
System.out.println();
} catch (Exception e) {
System.out.println("Sorry , no such type");
}
}
//使用商品的某個(gè)功能
public void testFuction(Object obj,String function){
try {
Class cla = obj.getClass();
//獲得cla類(lèi)中定義的無(wú)參方法。
Method m = cla.getMethod(function, null);
//調(diào)用obj中名為function的無(wú)參方法。
m.invoke(obj, null);
} catch (Exception e) {
System.out.println("Sorry , no such function");
}
}
//拿商品給顧客
public Object getCamera(String type){
try {
Class cla = Class.forName(type);
Object obj = cla.newInstance();
return obj;
} catch (Exception e) {
System.out.println("Sorry , no such type");
return null;
}
}
}