java反射机制系列(二)例子

下面我以顾客买相机为例来说明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 ptionZoom=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 ptionZoom=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 bj = 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 bj = cla.newInstance(); return obj; } catch (Exception e) { System.out.println("Sorry , no such type"); return null; }}}

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

不做任何解释。没有人明白,

java反射机制系列(二)例子

相关文章:

你感兴趣的文章:

标签云: