下面我以顧客買相機為例來說明Java反射機制的應用。例子中涉及的類和接口有:
Camera接口:定義了takePhoto()方法。
Camera01類:一種照相機的類型,實現Camera接口。
Camera02類:另一種照相機的類型,實現Camera接口。
Seller類:賣照相機。
Customer類:買相機,有main方法。
所有類都放在com包里
  程序如下:
public interface Camera {
    //聲明照相機必須可以拍照
 public void takePhoto();
}
public class Camera01 implements Camera {
 private final int prefixs =300;//300萬象素
 private final double optionZoom=3.5; //3.5倍變焦
 public void takePhoto() {
  System.out.println("Camera01 has taken a photo");
 }
}
類似的有
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");
 }
}
顧客出場了
public class Customer {
 public static void main(String[] args){
  //找到一個售貨員 
  Seller seller = new Seller();
  //向售貨員詢問兩種相機的信息
  seller.getDescription("com.Camera01");
  seller.getDescription("com.Camera02");
  //覺得Camera02比較好,叫售貨員拿來看
  Camera camera =(Camera)seller.getCamera("com.Camera02");
  //讓售貨員拍張照試一下
  seller.testFuction(camera, "takePhoto");
 }
}
Seller類通過Java反射機制實現
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Seller {
 //向顧客描述商品信息
 public void getDescription(String type){
  try {
   Class cla = Class.forName(type);
   //生成一個實例對象,在編譯時我們并不知道obj是什么類型。
   Object obj = cla.newInstance();
   //獲得type類型所有已定義類變量及方法。
   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);
    //輸出類變量的定義及obj實例中對應的值
    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++){
    //輸出類中方法的定義
    System.out.println(methods[i]);
   }
   System.out.println();
  } catch (Exception e) {
   System.out.println("Sorry , no such type");
  }
 }
 //使用商品的某個功能
 public void testFuction(Object obj,String function){
  try {
   Class cla = obj.getClass();
   //獲得cla類中定義的無參方法。
   Method m = cla.getMethod(function, null);
   //調用obj中名為function的無參方法。
   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;
  } 
 }
}
  程序到此結束,下一篇我將對程序進行分析,并補充一些內容。