Java的反射

来源:互联网 发布:深度linux桌面 编辑:程序博客网 时间:2024/06/04 19:51

Java的反射非常强大,传递class, 可以动态的生成该类、取得这个类的所有信息,包括里面的属性、方法以及构造函数等,甚至可以取得其父类或父接口里面的内容。

  obj.getClass().getDeclaredMethods();//取得obj类中自己定义的方法, 包括私有的方法。
  obj.getClass().getMethods();//取得obj类中自己定义的方法及继承过来的方法, 但私有方法得不到。
  同样, 对field也是一样,obj.getClass().getDeclaredFields();取得的是这个类中所有的属性,包括私有的field; 对obj.getClass().getFields();//取得是自己以及接继承来的属性, 但不能取得自己的私有属性。

Java代码  收藏代码
  1. static Object create(Class clazz) throws Exception {  
  2.     Constructor con = clazz.getConstructor(String.class);  
  3.     Object obj = con.newInstance("test name");  
  4.     return obj;  
  5.   }  
  6.   
  7.   static void invoke1(Object obj, String methodName)  
  8.       throws IllegalArgumentException, IllegalAccessException,  
  9.       InvocationTargetException, Exception, NoSuchMethodException {  
  10.     Method[] ms = obj.getClass().getDeclaredMethods();  
  11.     ms = obj.getClass().getMethods();  
  12.     for (Method m : ms) {  
  13.       // System.out.println(m.getName());  
  14.       if (methodName.equals(m.getName()))  
  15.         m.invoke(obj, null);  
  16.     }  
  17.   
  18.     Method m = obj.getClass().getMethod(methodName, null);  
  19.     m.invoke(obj, null);  
  20.   }  
  21.   
  22.   static void field(Class clazz) throws Exception {  
  23.     Field[] fs = clazz.getDeclaredFields();  
  24.     //fs = clazz.getFields();  
  25.     for (Field f : fs)  
  26.       System.out.println(f.getName());  
  27.   }  
  28.     
  29.   static void annon(Class clazz) throws Exception {  
  30.     Annotation[] as = clazz.getAnnotations();  
  31.   }  


  1. package com.yuqiaotech.simplejee.javase.reflect;  
  2.   
  3. import java.beans.BeanInfo;  
  4. import java.beans.Introspector;  
  5. import java.beans.PropertyDescriptor;  
  6. /** 
  7.  * 使用BeanInfo来设置和读取对象的属性。 
  8.  */  
  9. public class BeanInfoSample {  
  10.     static class User{  
  11.         private String username;  
  12.         private String password;  
  13.         private String gender;  
  14.         public String getUsername() {  
  15.             return username;  
  16.         }  
  17.         public void setUsername(String username) {  
  18.             this.username = username;  
  19.         }  
  20.         public String getPassword() {  
  21.             return password;  
  22.         }  
  23.         public void setPassword(String password) {  
  24.             this.password = password;  
  25.         }  
  26.         public String getGender() {  
  27.             return gender;  
  28.         }  
  29.         public void setGender(String gender) {  
  30.             this.gender = gender;  
  31.         }  
  32.     }  
  33.     public static void main(String[] args) throws Exception {  
  34.         User u = new User();  
  35.         u.setUsername("Tom");  
  36.         u.setPassword("123");  
  37.         u.setGender("male");  
  38.           
  39.         BeanInfo beanInfo = Introspector.getBeanInfo(User.class);  
  40.         PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();  
  41.         for (PropertyDescriptor pd : propertyDescriptors) {  
  42.             String proName = pd.getName();  
  43.             Object v = pd.getReadMethod().invoke(u, null);  
  44.             System.out.println(proName+"="+v);  
  45.         }  
  46.     }  
  47. }  


  1. package com.yuqiaotech.simplejee.javase.reflect;  
  2.   
  3. import java.lang.reflect.*;  
  4. /** 
  5.  * 1、获取类的相关信息 
  6.  * 2、知道类名,实例化出对象 
  7.  * 3、动态调用实例的方法 
  8.  *  
  9.  * 
  10.  */  
  11. public class ReflectSample {  
  12.     public static void main(String[] args) throws Exception {  
  13.         classInfo("com.yuqiaotech.simplejee.dao.BaseDao");  
  14.         newInstanceAndIncokeMethod();  
  15.     }  
  16.     private static void classInfo(String className) throws ClassNotFoundException{  
  17.         Class clazz = Class.forName(className);  
  18.           
  19.         System.out.println("all implemented interfaces");  
  20.         Class[] allInterfaces = clazz.getInterfaces();  
  21.         for (int i = 0; i < allInterfaces.length; i++) {  
  22.             System.out.println(i+"."+allInterfaces[i]);  
  23.         }  
  24.         System.out.println("all super classes");  
  25.         Class superClass = clazz.getSuperclass();  
  26.         int i = 0;  
  27.         while(superClass != null){  
  28.             System.out.println(++i+"."+superClass);  
  29.             superClass = superClass.getSuperclass();  
  30.         }  
  31.         System.out.println("methods");  
  32.         Method[] methods = clazz.getMethods();  
  33.         for (int j = 0; j < methods.length; j++) {  
  34.             Method m = methods[j];  
  35.             System.out.println(j+"."+m.getName());  
  36.         }  
  37.         System.out.println("getConstructors");  
  38.         int k = 0;  
  39.         Constructor[] cs = String.class.getConstructors();  
  40.         for (Constructor c : cs) {  
  41.             System.out.println(++k+"."+c);  
  42.         }  
  43.     }  
  44.     private static void newInstanceAndIncokeMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, ClassNotFoundException{  
  45.         class Point{  
  46.             int x;  
  47.             int y;  
  48.             public Point(int x, int y){  
  49.                 this.x = x;  
  50.                 this.y = y;  
  51.             }  
  52.             public Point(){  
  53.             }  
  54.             public int getX() {  
  55.                 return x;  
  56.             }  
  57.             public void setX(int x) {  
  58.                 this.x = x;  
  59.             }  
  60.             public int getY() {  
  61.                 return y;  
  62.             }  
  63.             public void setY(int y) {  
  64.                 this.y = y;  
  65.             }  
  66.             public double getDistant(){  
  67.                 return getDistant(0,0);  
  68.             }  
  69.             public double getDistant(int x, int y){  
  70.                 int x1 = this.x-x;  
  71.                 int y1 = this.y - y;  
  72.                 return Math.sqrt(x1*x1 + y1*y1);  
  73.             }  
  74.             public String toString(){  
  75.                 return "x="+x+",y="+y;  
  76.             }  
  77.         }  
  78.           
  79.         System.out.println("常规方式:");  
  80.         Point ox = new Point(3,4);  
  81.         System.out.println(ox);  
  82.         System.out.println("1111result="+ox.getDistant());  
  83.         System.out.println("1111result="+ox.getDistant(5,8));  
  84.           
  85.         System.out.println("反射方式:");  
  86.         //Class clazz = Point.class;  
  87.         Class clazz = Class.forName("com.yuqiaotech.simplejee.javase.reflect.ReflectSample$1Point");  
  88.         System.out.println("获取Point类的构造函数对象,使用该对象得到一个Point类的实例");  
  89.         //获取代表这个构造函数的对象public Point(int x, int y)  
  90.         Constructor c = clazz.getConstructor(int.classint.class);  
  91.         Object[] args = new Object[] {34};  
  92.         //Point o = new Point(3,4);  
  93.         Object o = c.newInstance(args);  
  94.         System.out.println(o);  
  95.         System.out.println("调用上述代码得到的实例的public double getDistant()方法,并执行它");  
  96.         //public double getDistant()  
  97.         Method m = clazz.getMethod("getDistant"null);  
  98.         //Double result = o.getDistant();  
  99.         Double result = (Double)m.invoke(o, null);  
  100.         System.out.println("result="+result);  
  101.         System.out.println("调用上述代码得到的实例的public double getDistant(int x, int y)方法," +  
  102.                 "并执行getDistant(5,8)");  
  103.         //public double getDistant(int x, int y)  
  104.         Method m2 = clazz.getMethod("getDistant"new Class[]{int.class,int.class});  
  105.         //Double result2 = o.getDistant(5,8);  
  106.         Double result2 = (Double)m2.invoke(o, new Integer[]{5,8});  
  107.         System.out.println("result2="+result2);  
  108.     }  
  109. }  

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 家里潮湿有异味怎么办 婚检白带有问题怎么办 体检前小便了怎么办 高考有英文纹身怎么办 高考手上有纹身怎么办 来大姨妈婚检怎么办 高考体检转氨酶偏高怎么办 播音主持有纹身怎么办 高考体检补不了怎么办 辅警体检不合格怎么办 小儿听力筛查未过关怎么办 宝宝听力没过关怎么办 护士体检有乙肝怎么办 高考体检表填错怎么办 高考体检表没有下载怎么办 警校视力没过怎么办 凉鞋挂钩总是脱怎么办 特别害怕抛妇产怎么办 抛妇产害怕紧张怎么办 毕业体检有乙肝怎么办? 宝宝胸围偏小怎么办 入园体检不合格怎么办 油表不显示油量怎么办 上大学体检不过怎么办 军校体检没过怎么办 六次化疗后怎么办 宝宝肚子有蛔虫怎么办 肾综激素依赖怎么办 胎儿阴囊有积液怎么办 中考学生英语很差怎么办 中考考得很差怎么办 科学总是考不好怎么办 初三学生数学不好怎么办 初三学生语文不好怎么办 初三学生英语不好怎么办 初三学生学习不好怎么办? 客户说不考虑怎么办 单位体检有乙肝怎么办 厂里体检出乙肝怎么办 厂里体检有乙肝怎么办 厂里体检查出乙肝怎么办