zoukankan      html  css  js  c++  java
  • java反射机制

    java反射机制

    动态创建实例,动态调用方法。

    1、通过一个对象获得完整的包名和类名 

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. /** 
    4.  * 通过一个对象获得完整的包名和类名 
    5.  * */  
    6. class Demo{  
    7.     //other codes...  
    8. }  
    9.    
    10. class hello{  
    11.     public static void main(String[] args) {  
    12.         Demo demo=new Demo();  
    13.         System.out.println(demo.getClass().getName());  
    14.     }  
    15. }  

    【运行结果】:Reflect.Demo 
    添加一句:所有类的对象其实都是Class的实例。 
    2、实例化Class类对象 

    Java代码  收藏代码
    1. package Reflect;  
    2. class Demo{  
    3.     //other codes...  
    4. }  
    5.    
    6. class hello{  
    7.     public static void main(String[] args) {  
    8.         Class<?> demo1=null;  
    9.         Class<?> demo2=null;  
    10.         Class<?> demo3=null;  
    11.         try{  
    12.             //一般尽量采用这种形式  
    13.             demo1=Class.forName("Reflect.Demo");  
    14.         }catch(Exception e){  
    15.             e.printStackTrace();  
    16.         }  
    17.         demo2=new Demo().getClass();  
    18.         demo3=Demo.class;  
    19.            
    20.         System.out.println("类名称   "+demo1.getName());  
    21.         System.out.println("类名称   "+demo2.getName());  
    22.         System.out.println("类名称   "+demo3.getName());  
    23.            
    24.     }  
    25. }  

     【运行结果】: 

    类名称   Reflect.Demo 

    类名称   Reflect.Demo 

    类名称   Reflect.Demo 

    3、通过Class实例化其他类的对象 
        通过无参构造实例化对象 

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. class Person{  
    4.        
    5.     public String getName() {  
    6.         return name;  
    7.     }  
    8.     public void setName(String name) {  
    9.         this.name = name;  
    10.     }  
    11.     public int getAge() {  
    12.         return age;  
    13.     }  
    14.     public void setAge(int age) {  
    15.         this.age = age;  
    16.     }  
    17.     @Override  
    18.     public String toString(){  
    19.         return "["+this.name+"  "+this.age+"]";  
    20.     }  
    21.     private String name;  
    22.     private int age;  
    23. }  
    24.    
    25. class hello{  
    26.     public static void main(String[] args) {  
    27.         Class<?> demo=null;  
    28.         try{  
    29.             demo=Class.forName("Reflect.Person");  
    30.         }catch (Exception e) {  
    31.             e.printStackTrace();  
    32.         }  
    33.         Person per=null;  
    34.         try {  
    35.             per=(Person)demo.newInstance();  
    36.         } catch (InstantiationException e) {  
    37.             // TODO Auto-generated catch block  
    38.             e.printStackTrace();  
    39.         } catch (IllegalAccessException e) {  
    40.             // TODO Auto-generated catch block  
    41.             e.printStackTrace();  
    42.         }  
    43.         per.setName("Rollen");  
    44.         per.setAge(20);  
    45.         System.out.println(per);  
    46.     }  
    47. }  

     【运行结果】: 

    [Rollen  20] 

    但是注意一下,当我们把Person中的默认的无参构造函数取消的时候,比如自己定义只定义一个有参数的构造函数之后,会出现错误: 

    比如我定义了一个构造函数:

    Java代码  收藏代码
    1. public Person(String name, int age) {  
    2.         this.age=age;  
    3.         this.name=name;  
    4.     }  

    然后继续运行上面的程序,会出现: 

    Java代码  收藏代码
    1. java.lang.InstantiationException: Reflect.Person  
    2.   
    3.     at java.lang.Class.newInstance0(Class.java:340)  
    4.   
    5.     at java.lang.Class.newInstance(Class.java:308)  
    6.   
    7.     at Reflect.hello.main(hello.java:39)  
    8.   
    9. Exception in thread "main" java.lang.NullPointerException  
    10.   
    11.     at Reflect.hello.main(hello.java:47)  

     所以大家以后再编写使用Class实例化其他类的对象的时候,一定要自己定义无参的构造函数 

    4、通过Class调用其他类中的构造函数 (也可以通过这种方式通过Class创建其他类的对象) 

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. import java.lang.reflect.Constructor;  
    4.    
    5. class Person{  
    6.        
    7.     public Person() {  
    8.            
    9.     }  
    10.     public Person(String name){  
    11.         this.name=name;  
    12.     }  
    13.     public Person(int age){  
    14.         this.age=age;  
    15.     }  
    16.     public Person(String name, int age) {  
    17.         this.age=age;  
    18.         this.name=name;  
    19.     }  
    20.     public String getName() {  
    21.         return name;  
    22.     }  
    23.     public int getAge() {  
    24.         return age;  
    25.     }  
    26.     @Override  
    27.     public String toString(){  
    28.         return "["+this.name+"  "+this.age+"]";  
    29.     }  
    30.     private String name;  
    31.     private int age;  
    32. }  
    33.    
    34. class hello{  
    35.     public static void main(String[] args) {  
    36.         Class<?> demo=null;  
    37.         try{  
    38.             demo=Class.forName("Reflect.Person");  
    39.         }catch (Exception e) {  
    40.             e.printStackTrace();  
    41.         }  
    42.         Person per1=null;  
    43.         Person per2=null;  
    44.         Person per3=null;  
    45.         Person per4=null;  
    46.         //取得全部的构造函数  
    47.         Constructor<?> cons[]=demo.getConstructors();  
    48.         try{  
    49.             per1=(Person)cons[0].newInstance();  
    50.             per2=(Person)cons[1].newInstance("Rollen");  
    51.             per3=(Person)cons[2].newInstance(20);  
    52.             per4=(Person)cons[3].newInstance("Rollen",20);  
    53.         }catch(Exception e){  
    54.             e.printStackTrace();  
    55.         }  
    56.         System.out.println(per1);  
    57.         System.out.println(per2);  
    58.         System.out.println(per3);  
    59.         System.out.println(per4);  
    60.     }  
    61. }  

     【运行结果】: 

    [null  0] 

    [Rollen  0] 

    [null  20] 

    [Rollen  20] 

    5、返回一个类实现的接口 

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. interface China{  
    4.     public static final String name="Rollen";  
    5.     public static  int age=20;  
    6.     public void sayChina();  
    7.     public void sayHello(String name, int age);  
    8. }  
    9.    
    10. class Person implements China{  
    11.     public Person() {  
    12.            
    13.     }  
    14.     public Person(String sex){  
    15.         this.sex=sex;  
    16.     }  
    17.     public String getSex() {  
    18.         return sex;  
    19.     }  
    20.     public void setSex(String sex) {  
    21.         this.sex = sex;  
    22.     }  
    23.     @Override  
    24.     public void sayChina(){  
    25.         System.out.println("hello ,china");  
    26.     }  
    27.     @Override  
    28.     public void sayHello(String name, int age){  
    29.         System.out.println(name+"  "+age);  
    30.     }  
    31.     private String sex;  
    32. }  
    33.    
    34. class hello{  
    35.     public static void main(String[] args) {  
    36.         Class<?> demo=null;  
    37.         try{  
    38.             demo=Class.forName("Reflect.Person");  
    39.         }catch (Exception e) {  
    40.             e.printStackTrace();  
    41.         }  
    42.         //保存所有的接口  
    43.         Class<?> intes[]=demo.getInterfaces();  
    44.         for (int i = 0; i < intes.length; i++) {  
    45.             System.out.println("实现的接口   "+intes[i].getName());  
    46.         }  
    47.     }  
    48. }  

     【运行结果】: 

    实现的接口   Reflect.China 

    6、取得其他类中的父类 

    Java代码  收藏代码
    1. class hello{  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo=null;  
    4.         try{  
    5.             demo=Class.forName("Reflect.Person");  
    6.         }catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         //取得父类  
    10.         Class<?> temp=demo.getSuperclass();  
    11.         System.out.println("继承的父类为:   "+temp.getName());  
    12.     }  
    13. }  

     【运行结果】 

    继承的父类为:   java.lang.Object 

    7、获得其他类中的全部构造函数 

    Java代码  收藏代码
    1. class hello{  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo=null;  
    4.         try{  
    5.             demo=Class.forName("Reflect.Person");  
    6.         }catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         Constructor<?>cons[]=demo.getConstructors();  
    10.         for (int i = 0; i < cons.length; i++) {  
    11.             System.out.println("构造方法:  "+cons[i]);  
    12.         }  
    13.     }  
    14. }  

     【运行结果】: 

    构造方法:  public Reflect.Person() 

    构造方法:  public Reflect.Person(java.lang.String) 

    但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符 

    下面这个例子我们就来获取修饰符 

    Java代码  收藏代码
    1. class hello{  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo=null;  
    4.         try{  
    5.             demo=Class.forName("Reflect.Person");  
    6.         }catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         Constructor<?>cons[]=demo.getConstructors();  
    10.         for (int i = 0; i < cons.length; i++) {  
    11.             Class<?> p[]=cons[i].getParameterTypes();  
    12.             System.out.print("构造方法:  ");  
    13.             int mo=cons[i].getModifiers();  
    14.             System.out.print(Modifier.toString(mo)+" ");  
    15.             System.out.print(cons[i].getName());  
    16.             System.out.print("(");  
    17.             for(int j=0;j<p.length;++j){  
    18.                 System.out.print(p[j].getName()+" arg"+i);  
    19.                 if(j<p.length-1){  
    20.                     System.out.print(",");  
    21.                 }  
    22.             }  
    23.             System.out.println("){}");  
    24.         }  
    25.     }  
    26. }  

     【运行结果】: 

    构造方法:  public Reflect.Person(){} 

    构造方法:  public Reflect.Person(java.lang.String arg1){} 

    有时候一个方法可能还有异常,呵呵。下面看看:

    Java代码  收藏代码
    1. class hello{  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo=null;  
    4.         try{  
    5.             demo=Class.forName("Reflect.Person");  
    6.         }catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         Method method[]=demo.getMethods();  
    10.         for(int i=0;i<method.length;++i){  
    11.             Class<?> returnType=method[i].getReturnType();  
    12.             Class<?> para[]=method[i].getParameterTypes();  
    13.             int temp=method[i].getModifiers();  
    14.             System.out.print(Modifier.toString(temp)+" ");  
    15.             System.out.print(returnType.getName()+"  ");  
    16.             System.out.print(method[i].getName()+" ");  
    17.             System.out.print("(");  
    18.             for(int j=0;j<para.length;++j){  
    19.                 System.out.print(para[j].getName()+" "+"arg"+j);  
    20.                 if(j<para.length-1){  
    21.                     System.out.print(",");  
    22.                 }  
    23.             }  
    24.             Class<?> exce[]=method[i].getExceptionTypes();  
    25.             if(exce.length>0){  
    26.                 System.out.print(") throws ");  
    27.                 for(int k=0;k<exce.length;++k){  
    28.                     System.out.print(exce[k].getName()+" ");  
    29.                     if(k<exce.length-1){  
    30.                         System.out.print(",");  
    31.                     }  
    32.                 }  
    33.             }else{  
    34.                 System.out.print(")");  
    35.             }  
    36.             System.out.println();  
    37.         }  
    38.     }  
    39. }  

     【运行结果】: 

    public java.lang.String  getSex () 

    public void  setSex (java.lang.String arg0) 

    public void  sayChina () 

    public void  sayHello (java.lang.String arg0,int arg1) 

    public final native void  wait (long arg0) throws java.lang.InterruptedException 

    public final void  wait () throws java.lang.InterruptedException 

    public final void  wait (long arg0,int arg1) throws java.lang.InterruptedException 

    public boolean  equals (java.lang.Object arg0) 

    public java.lang.String  toString () 

    public native int  hashCode () 

    public final native java.lang.Class  getClass () 

    public final native void  notify () 

    public final native void  notifyAll () 


    8、接下来让我们取得其他类的全部属性吧,最后我讲这些整理在一起,也就是通过class取得一个类的全部框架

    Java代码  收藏代码
    1. class hello {  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo = null;  
    4.         try {  
    5.             demo = Class.forName("Reflect.Person");  
    6.         } catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         System.out.println("===============本类属性========================");  
    10.         // 取得本类的全部属性  
    11.         Field[] field = demo.getDeclaredFields();  
    12.         for (int i = 0; i < field.length; i++) {  
    13.             // 权限修饰符  
    14.             int mo = field[i].getModifiers();  
    15.             String priv = Modifier.toString(mo);  
    16.             // 属性类型  
    17.             Class<?> type = field[i].getType();  
    18.             System.out.println(priv + " " + type.getName() + " "  
    19.                     + field[i].getName() + ";");  
    20.         }  
    21.         System.out.println("===============实现的接口或者父类的属性========================");  
    22.         // 取得实现的接口或者父类的属性  
    23.         Field[] filed1 = demo.getFields();  
    24.         for (int j = 0; j < filed1.length; j++) {  
    25.             // 权限修饰符  
    26.             int mo = filed1[j].getModifiers();  
    27.             String priv = Modifier.toString(mo);  
    28.             // 属性类型  
    29.             Class<?> type = filed1[j].getType();  
    30.             System.out.println(priv + " " + type.getName() + " "  
    31.                     + filed1[j].getName() + ";");  
    32.         }  
    33.     }  
    34. }  

    【运行结果】: 

    ===============本类属性======================== 

    private java.lang.String sex; 

    ===============实现的接口或者父类的属性======================== 

    public static final java.lang.String name; 

    public static final int age; 

    【案例】其实还可以通过反射调用其他类中的方法: 

    Java代码  收藏代码
    1. class hello {  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo = null;  
    4.         try {  
    5.             demo = Class.forName("Reflect.Person");  
    6.         } catch (Exception e) {  
    7.             e.printStackTrace();  
    8.         }  
    9.         try{  
    10.             //调用Person类中的sayChina方法  
    11.             Method method=demo.getMethod("sayChina");  
    12.             method.invoke(demo.newInstance());  
    13.             //调用Person的sayHello方法  
    14.             method=demo.getMethod("sayHello", String.class,int.class);  
    15.             method.invoke(demo.newInstance(),"Rollen",20);  
    16.                
    17.         }catch (Exception e) {  
    18.             e.printStackTrace();  
    19.         }  
    20.     }  
    21. }  

      【运行结果】: 

    hello ,china 

    Rollen  20 

    9、调用其他类的set和get方法 

    Java代码  收藏代码
    1. class hello {  
    2.     public static void main(String[] args) {  
    3.         Class<?> demo = null;  
    4.         Object obj=null;  
    5.         try {  
    6.             demo = Class.forName("Reflect.Person");  
    7.         } catch (Exception e) {  
    8.             e.printStackTrace();  
    9.         }  
    10.         try{  
    11.          obj=demo.newInstance();  
    12.         }catch (Exception e) {  
    13.             e.printStackTrace();  
    14.         }  
    15.         setter(obj,"Sex","男",String.class);  
    16.         getter(obj,"Sex");  
    17.     }  
    18.    
    19.     /** 
    20.      * @param obj 
    21.      *            操作的对象 
    22.      * @param att 
    23.      *            操作的属性 
    24.      * */  
    25.     public static void getter(Object obj, String att) {  
    26.         try {  
    27.             Method method = obj.getClass().getMethod("get" + att);  
    28.             System.out.println(method.invoke(obj));  
    29.         } catch (Exception e) {  
    30.             e.printStackTrace();  
    31.         }  
    32.     }  
    33.    
    34.     /** 
    35.      * @param obj 
    36.      *            操作的对象 
    37.      * @param att 
    38.      *            操作的属性 
    39.      * @param value 
    40.      *            设置的值 
    41.      * @param type 
    42.      *            参数的属性 
    43.      * */  
    44.     public static void setter(Object obj, String att, Object value,  
    45.             Class<?> type) {  
    46.         try {  
    47.             Method method = obj.getClass().getMethod("set" + att, type);  
    48.             method.invoke(obj, value);  
    49.         } catch (Exception e) {  
    50.             e.printStackTrace();  
    51.         }  
    52.     }  
    53. }// end class  

    【运行结果】: 

    男 


    10、通过反射操作属性 

    Java代码  收藏代码
    1. class hello {  
    2.     public static void main(String[] args) throws Exception {  
    3.         Class<?> demo = null;  
    4.         Object obj = null;  
    5.    
    6.         demo = Class.forName("Reflect.Person");  
    7.         obj = demo.newInstance();  
    8.    
    9.         Field field = demo.getDeclaredField("sex");  
    10.         field.setAccessible(true);  
    11.         field.set(obj, "男");  
    12.         System.out.println(field.get(obj));  
    13.     }  
    14. }// end class  

     11、通过反射取得并修改数组的信息:

    Java代码  收藏代码
    1. import java.lang.reflect.*;  
    2. class hello{  
    3.     public static void main(String[] args) {  
    4.         int[] temp={1,2,3,4,5};  
    5.         Class<?>demo=temp.getClass().getComponentType();  
    6.         System.out.println("数组类型: "+demo.getName());  
    7.         System.out.println("数组长度  "+Array.getLength(temp));  
    8.         System.out.println("数组的第一个元素: "+Array.get(temp, 0));  
    9.         Array.set(temp, 0, 100);  
    10.         System.out.println("修改之后数组第一个元素为: "+Array.get(temp, 0));  
    11.     }  
    12. }  

     【运行结果】: 

    数组类型: int 

    数组长度  5 

    数组的第一个元素: 1 

    修改之后数组第一个元素为: 100 

    12、通过反射修改数组大小 

    Java代码  收藏代码
    1. class hello{  
    2.     public static void main(String[] args) {  
    3.         int[] temp={1,2,3,4,5,6,7,8,9};  
    4.         int[] newTemp=(int[])arrayInc(temp,15);  
    5.         print(newTemp);  
    6.         System.out.println("=====================");  
    7.         String[] atr={"a","b","c"};  
    8.         String[] str1=(String[])arrayInc(atr,8);  
    9.         print(str1);  
    10.     }  
    11.        
    12.     /** 
    13.      * 修改数组大小 
    14.      * */  
    15.     public static Object arrayInc(Object obj,int len){  
    16.         Class<?>arr=obj.getClass().getComponentType();  
    17.         Object newArr=Array.newInstance(arr, len);  
    18.         int co=Array.getLength(obj);  
    19.         System.arraycopy(obj, 0, newArr, 0, co);  
    20.         return newArr;  
    21.     }  
    22.     /** 
    23.      * 打印 
    24.      * */  
    25.     public static void print(Object obj){  
    26.         Class<?>c=obj.getClass();  
    27.         if(!c.isArray()){  
    28.             return;  
    29.         }  
    30.         System.out.println("数组长度为: "+Array.getLength(obj));  
    31.         for (int i = 0; i < Array.getLength(obj); i++) {  
    32.             System.out.print(Array.get(obj, i)+" ");  
    33.         }  
    34.     }  
    35. }  

     【运行结果】: 
    数组长度为: 15 

    1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 ===================== 

    数组长度为: 8 

    a b c null null null null null 

    13、动态代理 
       如何获得类加载器: 

    Java代码  收藏代码
    1. class test{  
    2.        
    3. }  
    4. class hello{  
    5.     public static void main(String[] args) {  
    6.         test t=new test();  
    7.         System.out.println("类加载器  "+t.getClass().getClassLoader().getClass().getName());  
    8.     }  
    9. }  

     【程序输出】: 

    类加载器  sun.misc.Launcher$AppClassLoader 

    其实在java中有三种类类加载器。 

    1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。 

    2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jrelibext目录中的类 

    3)AppClassLoader 加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。 

    如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。

    Java代码  收藏代码
    1. package Reflect;  
    2. import java.lang.reflect.*;  
    3.    
    4. //定义项目接口  
    5. interface Subject {  
    6.     public String say(String name, int age);  
    7. }  
    8.    
    9. // 定义真实项目  
    10. class RealSubject implements Subject {  
    11.     @Override  
    12.     public String say(String name, int age) {  
    13.         return name + "  " + age;  
    14.     }  
    15. }  
    16.    
    17. class MyInvocationHandler implements InvocationHandler {  
    18.     private Object obj = null;  
    19.    
    20.     public Object bind(Object obj) {  
    21.         this.obj = obj;  
    22.         return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj  
    23.                 .getClass().getInterfaces(), this);  
    24.     }  
    25.    
    26.     @Override  
    27.     public Object invoke(Object proxy, Method method, Object[] args)  
    28.             throws Throwable {  
    29.         Object temp = method.invoke(this.obj, args);  
    30.         return temp;  
    31.     }  
    32. }  
    33.    
    34. class hello {  
    35.     public static void main(String[] args) {  
    36.         MyInvocationHandler demo = new MyInvocationHandler();  
    37.         Subject sub = (Subject) demo.bind(new RealSubject());  
    38.         String info = sub.say("Rollen", 20);  
    39.         System.out.println(info);  
    40.     }  
    41. }  

     【运行结果】: 

    Rollen  20 

    类的生命周期 

    在一个类编译完成之后,下一步就需要开始使用类,如果要使用一个类,肯定离不开JVM。在程序执行中JVM通过装载,链接,初始化这3个步骤完成。 

    类的装载是通过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,并且在堆区创建描述这个类的java.lang.Class对象。用来封装数据。 但是同一个类只会被类装载器装载以前 

    链接就是把二进制数据组装为可以运行的状态。 



    链接分为校验,准备,解析这3个阶段 

    校验一般用来确认此二进制文件是否适合当前的JVM(版本), 

    准备就是为静态成员分配内存空间,。并设置默认值 

    解析指的是转换常量池中的代码作为直接引用的过程,直到所有的符号引用都可以被运行程序使用(建立完整的对应关系) 

    完成之后,类型也就完成了初始化,初始化之后类的对象就可以正常使用了,直到一个对象不再使用之后,将被垃圾回收。释放空间。 

    当没有任何引用指向Class对象时就会被卸载,结束类的生命周期
     

    14、将反射用于工厂模式 

      如果不用反射的时候,的工厂模式吧: 

    Java代码  收藏代码
    1. /** 
    2.  * @author Rollen-Holt 设计模式之 工厂模式 
    3.  */  
    4.    
    5. interface fruit{  
    6.     public abstract void eat();  
    7. }  
    8.    
    9. class Apple implements fruit{  
    10.     public void eat(){  
    11.         System.out.println("Apple");  
    12.     }  
    13. }  
    14.    
    15. class Orange implements fruit{  
    16.     public void eat(){  
    17.         System.out.println("Orange");  
    18.     }  
    19. }  
    20.    
    21. // 构造工厂类  
    22. // 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了  
    23. class Factory{  
    24.     public static fruit getInstance(String fruitName){  
    25.         fruit f=null;  
    26.         if("Apple".equals(fruitName)){  
    27.             f=new Apple();  
    28.         }  
    29.         if("Orange".equals(fruitName)){  
    30.             f=new Orange();  
    31.         }  
    32.         return f;  
    33.     }  
    34. }  
    35. class hello{  
    36.     public static void main(String[] a){  
    37.         fruit f=Factory.getInstance("Orange");  
    38.         f.eat();  
    39.     }  
    40.    
    41. }  

     这样,当我们在添加一个子类的时候,就需要修改工厂类了。如果我们添加太多的子类的时候,改的就会很多。 

    现在我们看看利用反射机制:

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. interface fruit{  
    4.     public abstract void eat();  
    5. }  
    6.    
    7. class Apple implements fruit{  
    8.     public void eat(){  
    9.         System.out.println("Apple");  
    10.     }  
    11. }  
    12.    
    13. class Orange implements fruit{  
    14.     public void eat(){  
    15.         System.out.println("Orange");  
    16.     }  
    17. }  
    18.    
    19. class Factory{  
    20.     public static fruit getInstance(String ClassName){  
    21.         fruit f=null;  
    22.         try{  
    23.             f=(fruit)Class.forName(ClassName).newInstance();  
    24.         }catch (Exception e) {  
    25.             e.printStackTrace();  
    26.         }  
    27.         return f;  
    28.     }  
    29. }  
    30. class hello{  
    31.     public static void main(String[] a){  
    32.         fruit f=Factory.getInstance("Reflect.Apple");  
    33.         if(f!=null){  
    34.             f.eat();  
    35.         }  
    36.     }  
    37. }  

     现在就算我们添加任意多个子类的时候,工厂类就不需要修改。 



    上面的爱吗虽然可以通过反射取得接口的实例,但是需要传入完整的包和类名。而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。 

    下面我们来看看: 结合属性文件的工厂模式 

    首先创建一个fruit.properties的资源文件, 
    内容为: 

    Java代码  收藏代码
    1. apple=Reflect.Apple  
    2. orange=Reflect.Orange  

     然后编写主类代码: 

    Java代码  收藏代码
    1. package Reflect;  
    2.    
    3. import java.io.*;  
    4. import java.util.*;  
    5.    
    6. interface fruit{  
    7.     public abstract void eat();  
    8. }  
    9.    
    10. class Apple implements fruit{  
    11.     public void eat(){  
    12.         System.out.println("Apple");  
    13.     }  
    14. }  
    15.    
    16. class Orange implements fruit{  
    17.     public void eat(){  
    18.         System.out.println("Orange");  
    19.     }  
    20. }  
    21.    
    22. //操作属性文件类  
    23. class init{  
    24.     public static Properties getPro() throws FileNotFoundException, IOException{  
    25.         Properties pro=new Properties();  
    26.         File f=new File("fruit.properties");  
    27.         if(f.exists()){  
    28.             pro.load(new FileInputStream(f));  
    29.         }else{  
    30.             pro.setProperty("apple", "Reflect.Apple");  
    31.             pro.setProperty("orange", "Reflect.Orange");  
    32.             pro.store(new FileOutputStream(f), "FRUIT CLASS");  
    33.         }  
    34.         return pro;  
    35.     }  
    36. }  
    37.    
    38. class Factory{  
    39.     public static fruit getInstance(String ClassName){  
    40.         fruit f=null;  
    41.         try{  
    42.             f=(fruit)Class.forName(ClassName).newInstance();  
    43.         }catch (Exception e) {  
    44.             e.printStackTrace();  
    45.         }  
    46.         return f;  
    47.     }  
    48. }  
    49. class hello{  
    50.     public static void main(String[] a) throws FileNotFoundException, IOException{  
    51.         Properties pro=init.getPro();  
    52.         fruit f=Factory.getInstance(pro.getProperty("apple"));  
    53.         if(f!=null){  
    54.             f.eat();  
    55.         }  
    56.     }  
    57. }  

     【运行结果】:Apple 

    转自:http://lengchaotian.iteye.com/blog/1881992

  • 相关阅读:
    jade -Template Engine
    GitHub 版本管理工具
    Bootstrap笔记
    网页布局笔记
    html,css的笔记
    Angular 实例项目 angular-phonecat 的一些问题
    sublime 浏览器快捷键配置
    Javascript 事件 笔记 1
    Bootstrap 学习笔记 一
    Codeforces 546 E:士兵的旅行 最大网络流
  • 原文地址:https://www.cnblogs.com/harry335/p/4833007.html
Copyright © 2011-2022 走看看