Chinaunix首页 | 论坛 | 博客
  • 博客访问: 557177
  • 博文数量: 48
  • 博客积分: 4026
  • 博客等级: 上校
  • 技术积分: 622
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-26 13:59
文章分类

全部博文(48)

文章存档

2011年(3)

2010年(6)

2009年(12)

2008年(27)

我的朋友

分类: Java

2009-06-15 09:55:29

Reflection 是Java被视为动态(或准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等等)、superclass(例如Object)、实现之interfaces(例如Cloneable),也包括fields和methods的所有信息,并可于运行时改变fields内容或唤起methods。

个人理解就是在运行时可以得到某个对象的所有信息,包括方法,类型,属性,方法参数,方法返回值以及可以调用该类的所有方法。

下面是两个例子:

Java代码
  1. package cn.test;   
  2.   
  3.   
  4. import java.lang.reflect.Array;   
  5. import java.lang.reflect.Constructor;   
  6. import java.lang.reflect.Field;   
  7. import java.lang.reflect.Method;   
  8.   
  9.   
  10. /**  
  11.  * Java Reflection Cookbook  
  12.  *  
  13.  * @author Michael Lee  
  14.  * @since 2006-8-23  
  15.  * @version 0.1a  
  16.  */  
  17.   
  18. public class TestReflection {   
  19.     /**  
  20.      * 得到某个对象的公共属性  
  21.      *  
  22.      * @param owner, fieldName  
  23.      * @return 该属性对象  
  24.      * @throws Exception  
  25.      *  
  26.      */  
  27.     public Object getProperty(Object owner, String fieldName) throws Exception {   
  28.         Class ownerClass = owner.getClass();   
  29.   
  30.         Field field = ownerClass.getField(fieldName);   
  31.   
  32.         Object property = field.get(owner);   
  33.   
  34.         return property;   
  35.     }   
  36.   
  37.     /**  
  38.      * 得到某类的静态公共属性  
  39.      *  
  40.      * @param className   类名  
  41.      * @param fieldName   属性名  
  42.      * @return 该属性对象  
  43.      * @throws Exception  
  44.      */  
  45.     public Object getStaticProperty(String className, String fieldName)   
  46.             throws Exception {   
  47.         Class ownerClass = Class.forName(className);   
  48.   
  49.         Field field = ownerClass.getField(fieldName);   
  50.   
  51.         Object property = field.get(ownerClass);   
  52.   
  53.         return property;   
  54.     }   
  55.   
  56.   
  57.     /**  
  58.      * 执行某对象方法  
  59.      *  
  60.      * @param owner  
  61.      *            对象  
  62.      * @param methodName  
  63.      *            方法名  
  64.      * @param args  
  65.      *            参数  
  66.      * @return 方法返回值  
  67.      * @throws Exception  
  68.      */  
  69.     public Object invokeMethod(Object owner, String methodName, Object[] args)   
  70.             throws Exception {   
  71.   
  72.         Class ownerClass = owner.getClass();   
  73.   
  74.         Class[] argsClass = new Class[args.length];   
  75.   
  76.         for (int i = 0, j = args.length; i < j; i++) {   
  77.             argsClass[i] = args[i].getClass();   
  78.         }   
  79.   
  80.         Method method = ownerClass.getMethod(methodName, argsClass);   
  81.   
  82.         return method.invoke(owner, args);   
  83.     }   
  84.   
  85.   
  86.       /**  
  87.      * 执行某类的静态方法  
  88.      *  
  89.      * @param className  
  90.      *            类名  
  91.      * @param methodName  
  92.      *            方法名  
  93.      * @param args  
  94.      *            参数数组  
  95.      * @return 执行方法返回的结果  
  96.      * @throws Exception  
  97.      */  
  98.     public Object invokeStaticMethod(String className, String methodName,   
  99.             Object[] args) throws Exception {   
  100.         Class ownerClass = Class.forName(className);   
  101.   
  102.         Class[] argsClass = new Class[args.length];   
  103.   
  104.         for (int i = 0, j = args.length; i < j; i++) {   
  105.             argsClass[i] = args[i].getClass();   
  106.         }   
  107.   
  108.         Method method = ownerClass.getMethod(methodName, argsClass);   
  109.   
  110.         return method.invoke(null, args);   
  111.     }   
  112.   
  113.   
  114.   
  115.     /**  
  116.      * 新建实例  
  117.      *  
  118.      * @param className  
  119.      *            类名  
  120.      * @param args  
  121.      *            构造函数的参数  
  122.      * @return 新建的实例  
  123.      * @throws Exception  
  124.      */  
  125.     public Object newInstance(String className, Object[] args) throws Exception {   
  126.         Class newoneClass = Class.forName(className);   
  127.   
  128.         Class[] argsClass = new Class[args.length];   
  129.   
  130.         for (int i = 0, j = args.length; i < j; i++) {   
  131.             argsClass[i] = args[i].getClass();   
  132.         }   
  133.   
  134.         Constructor cons = newoneClass.getConstructor(argsClass);   
  135.   
  136.         return cons.newInstance(args);   
  137.   
  138.     }   
  139.   
  140.   
  141.        
  142.     /**  
  143.      * 是不是某个类的实例  
  144.      * @param obj 实例  
  145.      * @param cls 类  
  146.      * @return 如果 obj 是此类的实例,则返回 true  
  147.      */  
  148.     public boolean isInstance(Object obj, Class cls) {   
  149.         return cls.isInstance(obj);   
  150.     }   
  151.        
  152.     /**  
  153.      * 得到数组中的某个元素  
  154.      * @param array 数组  
  155.      * @param index 索引  
  156.      * @return 返回指定数组对象中索引组件的值  
  157.      */  
  158.     public Object getByArray(Object array, int index) {   
  159.         return Array.get(array,index);   
  160.     }   
  161. }  



Java代码 复制代码
  1. package cn.test;   
  2.   
  3. import java.lang.reflect.Field;   
  4. import java.lang.reflect.InvocationTargetException;   
  5. import java.lang.reflect.Method;   
  6. import java.util.ArrayList;   
  7.   
  8. import cn.IpUtils.IpBean;   
  9.   
  10. public class TestObject {   
  11.        
  12.     /**  
  13.      * 设置属性值  
  14.      * @param list  
  15.      * @param cla  
  16.      * @return  
  17.      */  
  18.     public ArrayList array2bean(ArrayList list, Class cla) {   
  19.         ArrayList result = new ArrayList();   
  20.         int filed_len = cla.getDeclaredFields().length;   
  21.         System.out.println(":"+cla.getDeclaredFields().length);   
  22.         for (int i = 0; i < list.size(); i++) {   
  23.             Object[] o = (Object[]) list.get(i);   
  24.             int length = filed_len < o.length ? filed_len : o.length;   
  25.             try {   
  26.                 result.add(cla.newInstance());   
  27.                 for (int j = 0; j < length; j++) {   
  28.                     Method m = null;   
  29.                     String mName =cla.getDeclaredFields()[j].getName();   
  30.                     mName = mName.substring(01).toUpperCase()+ mName.substring(1);   
  31.                     mName = "set" + mName;   
  32.                     m = cla.getMethod(mName, new Class[] { String.class });   
  33.                     //调用设置的方法,给属性赋值   
  34.                     m.invoke(result.get(i), new Object[] { o[j] == null ? "": o[j].toString() });   
  35.                 }   
  36.             } catch (Exception e) {   
  37.                 e.printStackTrace();   
  38.             }   
  39.         }   
  40.         return result;   
  41.     }   
  42.        
  43.     /**  
  44.      * 获取get的取值  
  45.      * @param obj  
  46.      * @return  
  47.      * @throws Exception  
  48.      */  
  49.     public String getObjectToString(Object obj) throws Exception{   
  50.         Class cla=obj.getClass();   
  51.         Method[] ma=cla.getDeclaredMethods();//获取所有声明的方法数组   
  52.         Method method=null;   
  53.         String methodName=null;   
  54.         Object returnValue=null;   
  55.         for(int i=0;i
  56.             method=ma[i];   
  57.             methodName=method.getName();//方法名   
  58.             if(methodName.indexOf("get")==0){//以get开始的方法,排除set方法   
  59.                 returnValue=method.invoke(obj, null);//调用方法,相当于执行get方法得到的结果,这里返回的是一个对象   
  60.                 System.out.print(methodName+"::");   
  61.                 System.out.println(returnValue==null?"":returnValue.toString());   
  62.             }   
  63.         }          
  64.         return "";   
  65.     }   
  66.   
  67.     /**  
  68.      * 获取对象的属性值,含有get方法的  
  69.      * @param obj  
  70.      * @return  
  71.      * @throws NoSuchMethodException   
  72.      * @throws SecurityException   
  73.      * @throws InvocationTargetException   
  74.      * @throws IllegalAccessException   
  75.      * @throws IllegalArgumentException   
  76.      */  
  77.     public String getAttributeValue(Object obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{   
  78.         Class cla=obj.getClass();   
  79.         Field[] fds=cla.getDeclaredFields();   
  80.         Field field=null;   
  81.         String fieldName=null;   
  82.         String methodName=null;   
  83.         Method method=null;   
  84.         Object returnValue=null;   
  85.         for(int i=0;i
  86.             field=fds[i];   
  87.             fieldName=field.getName();   
  88.             methodName="get"+fieldName.substring(01).toUpperCase()+fieldName.substring(1);               
  89.             method=cla.getDeclaredMethod(methodName, null);   
  90.             returnValue=method.invoke(obj, null);//调用方法,相当于执行get方法得到的结果,这里返回的是一个对象   
  91.             System.out.print(methodName+"::");   
  92.             System.out.println(returnValue==null?"":returnValue.toString());   
  93.         }   
  94.            
  95.         return "";   
  96.     }   
  97.        
  98.     /**  
  99.      * @param args  
  100.      * @throws Exception   
  101.      */  
  102.     public static void main(String[] args) throws Exception {   
  103. //      IpBean.class   
  104.         TestObject to=new TestObject();   
  105.         IpBean ib=new IpBean();   
  106.         ib.setFrom("from1");   
  107.         ib.setPosition("position1");   
  108.         ib.setTo("to1");   
  109.         ib.setId(10);   
  110.         to.getObjectToString(ib);   
  111. //      to.getAttributeValue(ib);   
  112.     }   
  113.   
  114. }  
阅读(952) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~