java反射机制(二)例子

xiaoxiao2026-03-16  7

下面我以顾客买相机为例来说明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; } } }

 程序到此结束,下一篇我将对程序进行分析,并补充一些内容。

转载请注明原文地址: https://www.6miu.com/read-5046019.html

最新回复(0)