java反射详解 (一)

 【案例1】经过一个对象得到完整的包名和类名java

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

 

【运行结果】:Reflect.Demo数组

添加一句:全部类的对象其实都是Class的实例。框架

【案例2】实例化Class类对象ide

 

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

 

  
  
  
  
  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, 0100); 
  10.         System.out.println("修改以后数组第一个元素为: "+Array.get(temp, 0)); 
  11.     } 

【案例3】经过Class实例化其余类的对象函数

经过无参构造实例化对象this

  
  
  
  
  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. class hello{ 
  25.     public static void main(String[] args) { 
  26.         Class<?> demo=null
  27.         try
  28.             demo=Class.forName("Reflect.Person"); 
  29.         }catch (Exception e) { 
  30.             e.printStackTrace(); 
  31.         } 
  32.         Person per=null
  33.         try { 
  34.             per=(Person)demo.newInstance(); 
  35.         } catch (InstantiationException e) { 
  36.             // TODO Auto-generated catch block 
  37.             e.printStackTrace(); 
  38.         } catch (IllegalAccessException e) { 
  39.             // TODO Auto-generated catch block 
  40.             e.printStackTrace(); 
  41.         } 
  42.         per.setName("Rollen"); 
  43.         per.setAge(20); 
  44.         System.out.println(per); 
  45.     } 

 

 

【运行结果】: spa

[Rollen  20]code

可是注意一下,当咱们把Person中的默认的无参构造函数取消的时候,好比本身定义只定义一个有参数的构造函数以后,会出现错误: orm

好比我定义了一个构造函数:对象

  
  
  
  
  1. public Person(String name, int age) { 
  2.         this.age=age; 
  3.         this.name=name; 
  4.     } 

 

 

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

java.lang.InstantiationException: Reflect.Person

    at java.lang.Class.newInstance0(Class.java:340)

    at java.lang.Class.newInstance(Class.java:308)

    at Reflect.hello.main(hello.java:39)

Exception in thread "main" java.lang.NullPointerException

    at Reflect.hello.main(hello.java:47)

因此你们之后再编写使用Class实例化其余类的对象的时候,必定要本身定义无参的构造函数

 

【案例】经过Class调用其余类中的构造函数 (也能够经过这种方式经过Class建立其余类的对象)

  
  
  
  
  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. class hello{ 
  34.     public static void main(String[] args) { 
  35.         Class<?> demo=null
  36.         try
  37.             demo=Class.forName("Reflect.Person"); 
  38.         }catch (Exception e) { 
  39.             e.printStackTrace(); 
  40.         } 
  41.         Person per1=null
  42.         Person per2=null
  43.         Person per3=null
  44.         Person per4=null
  45.         //取得所有的构造函数 
  46.         Constructor<?> cons[]=demo.getConstructors(); 
  47.         try
  48.             per1=(Person)cons[0].newInstance(); 
  49.             per2=(Person)cons[1].newInstance("Rollen"); 
  50.             per3=(Person)cons[2].newInstance(20); 
  51.             per4=(Person)cons[3].newInstance("Rollen",20); 
  52.         }catch(Exception e){ 
  53.             e.printStackTrace(); 
  54.         } 
  55.         System.out.println(per1); 
  56.         System.out.println(per2); 
  57.         System.out.println(per3); 
  58.         System.out.println(per4); 
  59.     } 

 

 

【运行结果】:

[null  0]

[Rollen  0]

[null  20]

[Rollen  20]

【案例】 

返回一个类实现的接口:

  
  
  
  
  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. class Person implements China{ 
  10.     public Person() { 
  11.           
  12.     } 
  13.     public Person(String sex){ 
  14.         this.sex=sex; 
  15.     } 
  16.     public String getSex() { 
  17.         return sex; 
  18.     } 
  19.     public void setSex(String sex) { 
  20.         this.sex = sex; 
  21.     } 
  22.     @Override 
  23.     public void sayChina(){ 
  24.         System.out.println("hello ,china"); 
  25.     } 
  26.     @Override 
  27.     public void sayHello(String name, int age){ 
  28.         System.out.println(name+"  "+age); 
  29.     } 
  30.     private String sex; 
  31.   
  32. class hello{ 
  33.     public static void main(String[] args) { 
  34.         Class<?> demo=null
  35.         try
  36.             demo=Class.forName("Reflect.Person"); 
  37.         }catch (Exception e) { 
  38.             e.printStackTrace(); 
  39.         } 
  40.         //保存全部的接口 
  41.         Class<?> intes[]=demo.getInterfaces(); 
  42.         for (int i = 0; i < intes.length; i++) { 
  43.             System.out.println("实现的接口   "+intes[i].getName()); 
  44.         } 
  45.     } 

 

 

【运行结果】:

实现的接口   Reflect.China

(注意,如下几个例子,都会用到这个例子的Person类,因此为节省篇幅,此处再也不粘贴Person的代码部分,只粘贴主类hello的代码)

【案例】:取得其余类中的父类

  
  
  
  
  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.     } 

 

 

【运行结果】

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

【案例】:得到其余类中的所有构造函数

这个例子须要在程序开头添加import java.lang.reflect.*;

而后将主类编写为:

  
  
  
  
  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.     } 

 

 

【运行结果】:

构造方法:  public Reflect.Person()

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

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

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

  
  
  
  
  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.     } 

 

 

【运行结果】:

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

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

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

  
  
  
  
  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.     } 

 

【运行结果】:

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 ()

【案例】接下来让咱们取得其余类的所有属性吧,最后我讲这些整理在一块儿,也就是经过class取得一个类的所有框架

  
  
  
  
  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.     } 

 

 

【运行结果】:

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

private java.lang.String sex;

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

public static final java.lang.String name;

public static final int age;

【案例】其实还能够经过反射调用其余类中的方法:

  
  
  
  
  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.     } 

 

 

【运行结果】:

hello ,china

Rollen  20

【案例】调用其余类的setget方法

  
  
  
  
  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 

 

【运行结果】:

相关文章
相关标签/搜索