反射

来源:互联网 发布:尚品奥莱软件 编辑:程序博客网 时间:2024/05/16 06:26

 

Java提供了一套机制来动态执行方法和构造方法,以及数组操作等,这套机制就叫——反射。反射机制是如今很多流行框架的实现基础,其中包括SpringHibernate等。原理性的问题不是本文的重点,接下来让我们在实例中学习这套精彩的机制。

1.得到某个对象的属性

1.     public Object getProperty(Object owner, String fieldName) throws Exception {         

2.         Class ownerClass = owner.getClass();                                             

3.                                                                                          

4.         Field field = ownerClass.getField(fieldName);                                    

5.                                                                                          

6.         Object property = field.get(owner);                                              

7.                                                                                          

8.         return property;                                                                 

9.     }       

                                                                            

ClassownerClass = owner.getClass():得到该对象的Class

Fieldfield = ownerClass.getField(fieldName):通过Class得到类声明的属性。

Objectproperty = field.get(owner):通过对象得到该属性的实例,如果这个属性是非公有的,这里会报IllegalAccessException

2.得到某个类的静态属性

1.     public Object getStaticProperty(String className, String fieldName)       

2.                 throws Exception {                                            

3.         Class ownerClass = Class.forName(className);                          

4.                                                                               

5.         Field field = ownerClass.getField(fieldName);                         

6.                                                                               

7.         Object property = field.get(ownerClass);                              

8.                                                                               

9.         return property;                                                      

10.  }                

                                                        

ClassownerClass = Class.forName(className) :首先得到这个类的Class

Fieldfield = ownerClass.getField(fieldName):和上面一样,通过Class得到类声明的属性。

Objectproperty = field.get(ownerClass) :这里和上面有些不同,因为该属性是静态的,所以直接从类的Class里取。


3.
执行某对象的方法

1.     public Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {      

2.         Class ownerClass = owner.getClass();      

3.         Class[] argsClass = new Class[args.length];      

4.         for (int i = 0, j = args.length; i < j; i++) {      

5.             argsClass[i] = args[i].getClass();      

6.         }       

7.         Method method = ownerClass.getMethod(methodName, argsClass);         

8.         return method.invoke(owner, args);       

9.     }     


Class owner_class = owner.getClass()
:首先还是必须得到这个对象的Class

36行:配置参数的Class数组,作为寻找Method的条件。

Methodmethod = ownerClass.getMethod(methodName, argsClass):通过Method名和参数的Class数组得到要执行的Method

method.invoke(owner,args):执行该Methodinvoke方法的参数是执行这个方法的对象,和参数数组。返回值是Object,也既是该方法的返回值。


4.
执行某个类的静态方法

1.     public Object invokeStaticMethod(String className, String methodName,               

2.                 Object[] args) throws Exception {                                       

3.         Class ownerClass = Class.forName(className);                                    

4.                                                                                         

5.         Class[] argsClass = new Class[args.length];                                     

6.                                                                                         

7.         for (int i = 0, j = args.length; i < j; i++) {                                  

8.             argsClass[i] = args[i].getClass();                                          

9.         }                                                                               

10.                                                                                      

11.      Method method = ownerClass.getMethod(methodName, argsClass);                    

12.                                                                                      

13.      return method.invoke(null, args);                                               

14.  }          

                                                                         
基本的原理和实例3相同,不同点是最后一行,invoke的一个参数是null,因为这是静态方法,不需要借助实例运行。

5.新建实例

1.     public Object newInstance(String className, Object[] args) throws Exception {       

2.         Class newoneClass = Class.forName(className);                                   

3.                                                                                         

4.         Class[] argsClass = new Class[args.length];                                     

5.                                                                                         

6.         for (int i = 0, j = args.length; i < j; i++) {                                  

7.             argsClass[i] = args[i].getClass();                                          

8.         }                                                                               

9.                                                                                         

10.      Constructor cons = newoneClass.getConstructor(argsClass);                       

11.                                                                                      

12.      return cons.newInstance(args);                                                  

13.                                                                                      

14.  }           

                                                                        
这里说的方法是执行带参数的构造函数来新建实例的方法。如果不需要参数,可以直接使用newoneClass.newInstance()来实现。

ClassnewoneClass = Class.forName(className):第一步,得到要构造的实例的Class

6~第10行:得到参数的Class数组。

1.     Constructor cons = newoneClass.getConstructor(argsClass):得到构造子。   

2.       

3.     cons.newInstance(args):新建实例。   


6.
判断是否为某个类的实例

1.     public boolean isInstance(Object obj, Class cls) {           

2.         return cls.isInstance(obj);                              

3.     }             

                                              

7.得到数组中的某个元素

1.     public Object getByArray(Object array, int index) {          

2.         return Array.get(array,index);                           

3.     }                    

                                       

附完整源码:

1.     import java.lang.reflect.Array;      

2.     import java.lang.reflect.Constructor;      

3.     import java.lang.reflect.Field;      

4.     import java.lang.reflect.Method;      

5.          

6.          

7.     /**     

8.      * Java Reflection Cookbook     

9.      *     

10.   * @author Michael Lee     

11.   * @since 2006-8-23     

12.   * @version 0.1a     

13.   */      

14.        

15.  public class Reflection {      

16.      /**     

17.       * 得到某个对象的公共属性     

18.       *     

19.       * @param owner, fieldName     

20.       * @return 该属性对象     

21.       * @throws Exception     

22.       *     

23.       */      

24.      public Object getProperty(Object owner, String fieldName) throws Exception {      

25.          Class ownerClass = owner.getClass();      

26.        

27.          Field field = ownerClass.getField(fieldName);      

28.        

29.          Object property = field.get(owner);      

30.        

31.          return property;      

32.      }      

33.        

34.      /**     

35.       * 得到某类的静态公共属性     

36.       *     

37.       * @param className   类名     

38.       * @param fieldName   属性名     

39.       * @return 该属性对象     

40.       * @throws Exception     

41.       */      

42.      public Object getStaticProperty(String className, String fieldName)      

43.              throws Exception {      

44.          Class ownerClass = Class.forName(className);      

45.        

46.          Field field = ownerClass.getField(fieldName);      

47.        

48.          Object property = field.get(ownerClass);      

49.        

50.          return property;      

51.      }      

52.        

53.        

54.      /**     

55.       * 执行某对象方法     

56.       *     

57.       * @param owner     

58.       *            对象     

59.       * @param methodName     

60.       *            方法名     

61.       * @param args     

62.       *            参数     

63.       * @return 方法返回值     

64.       * @throws Exception     

65.       */      

66.      public Object invokeMethod(Object owner, String methodName, Object[] args)      

67.              throws Exception {      

68.        

69.          Class ownerClass = owner.getClass();      

70.        

71.          Class[] argsClass = new Class[args.length];      

72.        

73.          for (int i = 0, j = args.length; i < j; i++) {      

74.              argsClass[i] = args[i].getClass();      

75.          }      

76.        

77.          Method method = ownerClass.getMethod(methodName, argsClass);      

78.        

79.          return method.invoke(owner, args);      

80.      }      

81.        

82.        

83.        /**     

84.       * 执行某类的静态方法     

85.       *     

86.       * @param className     

87.       *            类名     

88.       * @param methodName     

89.       *            方法名     

90.       * @param args     

91.       *            参数数组     

92.       * @return 执行方法返回的结果     

93.       * @throws Exception     

94.       */      

95.      public Object invokeStaticMethod(String className, String methodName,      

96.              Object[] args) throws Exception {      

97.          Class ownerClass = Class.forName(className);      

98.        

99.          Class[] argsClass = new Class[args.length];      

100.        

101.          for (int i = 0, j = args.length; i < j; i++) {      

102.              argsClass[i] = args[i].getClass();      

103.          }      

104.        

105.          Method method = ownerClass.getMethod(methodName, argsClass);      

106.        

107.          return method.invoke(null, args);      

108.      }      

109.        

110.        

111.        

112.      /**     

113.       * 新建实例     

114.       *     

115.       * @param className     

116.       *            类名     

117.       * @param args     

118.       *            构造函数的参数     

119.       * @return 新建的实例     

120.       * @throws Exception     

121.       */      

122.      public Object newInstance(String className, Object[] args) throws Exception {      

123.          Class newoneClass = Class.forName(className);      

124.        

125.          Class[] argsClass = new Class[args.length];      

126.        

127.          for (int i = 0, j = args.length; i < j; i++) {      

128.              argsClass[i] = args[i].getClass();      

129.          }      

130.        

131.          Constructor cons = newoneClass.getConstructor(argsClass);      

132.        

133.          return cons.newInstance(args);      

134.        

135.      }      

136.        

137.        

138.            

139.      /**     

140.       * 是不是某个类的实例     

141.       * @param obj 实例     

142.       * @param cls      

143.       * @return 如果 obj 是此类的实例,则返回 true     

144.       */      

145.      public boolean isInstance(Object obj, Class cls) {      

146.          return cls.isInstance(obj);      

147.      }      

148.            

149.      /**     

150.       * 得到数组中的某个元素     

151.       * @param array 数组     

152.       * @param index 索引     

153.       * @return 返回指定数组对象中索引组件的值     

154.       */      

155.      public Object getByArray(Object array, int index) {      

156.          return Array.get(array,index);      

157.      }      

158.  }      

159.    

java反射实现例子

 

1.     **  

2.       * getCntrFromEdi  

3.      

4.       * @param ediFileBean  

5.       * @param iMainkey  

6.       * @param cntrno  

7.       * @return  

8.       */  

9.      public Object getCntrFromEdi(EdiFileBean ediFileBean,int iMainkey,String cntrno){  

10.    try {   

11.     ArrayList cntrList = (ArrayList)ediFileBean.getCntrHt().get(iMainkey);  

12.     if(cntrList!=null && cntrList.size()>0){   

13.      for(int i = 0;i<cntrList.size();i++){   

14.       Object objCntr = cntrList.get(i);  

15.          

16.       Class clEdiBkcntr = objCntr.getClass();  

17.       Method method;  

18.       method = clEdiBkcntr.getMethod("getCntrno",null);   

19.            

20.       Object[] arg = new Object[0];   

21.       String cntrnoTmp = "";   

22.       cntrnoTmp = (String)method.invoke(objCntr, arg);  

23.          

24.       if(cntrno.equals(cntrnoTmp)){   

25.        return objCntr;   

26.       }   

27.      }   

28.     }   

29.    } catch (SecurityException e) {  

30.     // TODO Auto-generated catch block   

31.     e.printStackTrace();  

32.    } catch (NoSuchMethodException e) {  

33.     // TODO Auto-generated catch block   

34.     e.printStackTrace();  

35.    } catch (IllegalArgumentException e) {  

36.     // TODO Auto-generated catch block   

37.     e.printStackTrace();  

38.    } catch (IllegalAccessException e) {  

39.     // TODO Auto-generated catch block   

40.     e.printStackTrace();  

41.    } catch (InvocationTargetException e) {  

42.     // TODO Auto-generated catch block   

43.     e.printStackTrace();  

44.    }    

45.    return null;   

46.   }   

47.    

java反射机制——克隆

 

1.     package com.dreamsoft.reflect;   

2.       

3.     import java.lang.reflect.Constructor;  

4.     import java.lang.reflect.Field;   

5.     import java.lang.reflect.InvocationTargetException;  

6.     import java.lang.reflect.Method;   

7.       

8.     import com.sun.java_cup.internal.internal_error;  

9.       

10.    

11.  public class ReflectTest {   

12.   private int id;   

13.   public String user = "zenghao";   

14.      

15.      

16.      

17.   public ReflectTest() {   

18.    super();   

19.   }   

20.    

21.   public ReflectTest(int id, String user) {  

22.    super();   

23.    this.id = id;   

24.    this.user = user;   

25.   }   

26.    

27.   public int getId() {   

28.    return id;   

29.   }   

30.    

31.   public void setId(int id) {   

32.    this.id = id;   

33.   }   

34.    

35.   public String getUser() {  

36.    return user;   

37.   }   

38.    

39.   public void setUser(String user) {  

40.    this.user = user;   

41.   }   

42.      

43.   public static void main(String[] args) {  

44.    //class定义:正在运行的 Java 应用程序中的类和接口   

45.    Class cla =ReflectTest.class;//得到类的CLASS   

46.   //===========      获取所有属性,方法,构造器         =============    

47.  //  Method[] method = cla.getMethods();//获取所有方法的完整名字   

48.  //  for (int i = 0; i < method.length; i++) {   

49.  //   System.out.println(method[i].getName());   

50.  //  }   

51.       

52.  //  Field[] f = cla.getFields();//获得公有属性完整名字   

53.  //  for (int i = 0; i < f.length; i++) {   

54.  //   System.out.println(f[i].getName());//公有属性名字   

55.  //  }   

56.  //     

57.  //  Field[] f2 = cla.getDeclaredFields();//获得所有属性完整名字   

58.  //  for (int i = 0; i < f2.length; i++) {   

59.  //   System.out.println(f2[i].getName());   

60.  //  }   

61.       

62.  //  Constructor[] constr =  cla.getConstructors();//获取所有构造器   

63.  //  for (int i = 0; i < constr.length; i++) {   

64.  //   System.out.println(constr[i].getName());   

65.  //  }   

66.      

67.       

68.       

69.  //  ===========      获取某个方法 并使用反射执行        =============    

70.    Object test = new ReflectTest();//生成实例   

71.    try {   

72.     //获得setId方法   

73.        

74.     Method method = cla.getDeclaredMethod("setId"new Class[]{int.class});   

75.     method.invoke(test, new Object[]{11});//使用反射执行方法   

76.    

77.     //获得setName方法   

78.     Method method2 = cla.getDeclaredMethod("setUser"new Class[]{String.class});   

79.     method2.invoke(test, new Object[]{"zenghao2"});//使用反射执行方法   

80.        

81.     //获得getId方法   

82.     Method method3 = cla.getDeclaredMethod("getId",null);   

83.     Object i  = method3.invoke(test,null);//使用反射执行方法   

84.     System.out.println(i.getClass());  

85.        

86.     //获得getName方法   

87.     Method method4 = cla.getDeclaredMethod("getUser"null);   

88.     Object name =  method4.invoke(test, null);   

89.     System.out.println(name);  

90.    } catch (SecurityException e) {  

91.     // TODO Auto-generated catch block   

92.     e.printStackTrace();  

93.    } catch (NoSuchMethodException e) {  

94.     // TODO Auto-generated catch block   

95.     e.printStackTrace();  

96.    } catch (IllegalArgumentException e) {  

97.     // TODO Auto-generated catch block   

98.     e.printStackTrace();  

99.    } catch (IllegalAccessException e) {  

100.     // TODO Auto-generated catch block   

101.     e.printStackTrace();  

102.    } catch (InvocationTargetException e) {  

103.     // TODO Auto-generated catch block   

104.     e.printStackTrace();  

105.    }   

106.       

107.    try {   

108.     ReflectUtil.invokeSetMethodByName(test, "setUser"new Object[]{"zenghao3"});   

109.     System.out.println(ReflectUtil.invokeGetMethodWithoutParameter(test, "getUser"));   

110.    } catch (Exception e) {   

111.     // TODO Auto-generated catch block   

112.     e.printStackTrace();  

113.    }   

114.       

115.    }   

116.      

117.  }   

Reflection-判断一个方法是否有注释-Java源码

 

判断一个方法是否有注释

1.     import java.lang.annotation.Retention;  

2.     import java.lang.annotation.RetentionPolicy;  

3.     import java.lang.reflect.Method;   

4.       

5.     @Retention(RetentionPolicy.RUNTIME)   

6.     @interface MyMarker {   

7.     }  

8.       

9.     class Marker {   

10.    @MyMarker  

11.    public static void myMeth() {   

12.      Marker ob = new Marker();   

13.    

14.      try {   

15.        Method m = ob.getClass().getMethod("myMeth");   

16.    

17.        if (m.isAnnotationPresent(MyMarker.class))   

18.          System.out.println("MyMarker is present.");   

19.    

20.      } catch (NoSuchMethodException exc) {  

21.        System.out.println("Method Not Found.");   

22.      }   

23.    }   

24.    

25.    public static void main(String args[]) {  

26.      myMeth();  

27.    }   

28.  }   

29.    

Reflection-设定注释的默认值-Java源码

 

设定注释的默认值

1.     import java.lang.annotation.Retention;  

2.     import java.lang.annotation.RetentionPolicy;  

3.     import java.lang.reflect.Method;   

4.       

5.     @Retention(RetentionPolicy.RUNTIME)   

6.     @interface MyAnno {   

7.       String str() default "Testing";   

8.       

9.       int val() default 9000;   

10.  }   

11.    

12.  class Meta3 {   

13.    @MyAnno()   

14.    public static void myMeth() {   

15.      Meta3 ob = new Meta3();   

16.    

17.      try {   

18.        Class c = ob.getClass();  

19.    

20.        Method m = c.getMethod("myMeth");   

21.    

22.        MyAnno anno = m.getAnnotation(MyAnno.class);   

23.    

24.        System.out.println(anno.str() + " " + anno.val());   

25.      } catch (NoSuchMethodException exc) {  

26.        System.out.println("Method Not Found.");   

27.      }   

28.    }   

29.    

30.    public static void main(String args[]) {  

31.      myMeth();  

32.    }   

33.  }   

Reflection-显示类中所有注释-Java源码

 

显示类中所有注释

1.     import java.lang.annotation.Annotation;  

2.     import java.lang.annotation.Retention;  

3.     import java.lang.annotation.RetentionPolicy;  

4.     import java.lang.reflect.Method;   

5.       

6.     @Retention(RetentionPolicy.RUNTIME)   

7.     @interface MyAnno {   

8.       String str();  

9.       

10.    int val();   

11.  }   

12.    

13.  @Retention(RetentionPolicy.RUNTIME)   

14.  @interface What {   

15.    String description();  

16.  }   

17.    

18.  @What(description = "An annotation test class")   

19.  @MyAnno(str = "Meta2", val = 99)   

20.  class Meta2 {   

21.    

22.    @What(description = "An annotation test method")   

23.    @MyAnno(str = "Testing", val = 100)   

24.    public static void myMeth() {   

25.      Meta2 ob = new Meta2();   

26.    

27.      try {   

28.        Annotation annos[] = ob.getClass().getAnnotations();  

29.    

30.        System.out.println("All annotations for Meta2:");   

31.        for (Annotation a : annos)  

32.          System.out.println(a);  

33.    

34.        Method m = ob.getClass().getMethod("myMeth");   

35.        annos = m.getAnnotations();  

36.    

37.        System.out.println("All annotations for myMeth:");   

38.        for (Annotation a : annos)  

39.          System.out.println(a);  

40.    

41.      } catch (NoSuchMethodException exc) {  

42.        System.out.println("Method Not Found.");   

43.      }   

44.    }   

45.    

46.    public static void main(String args[]) {  

47.      myMeth();  

48.    }   

49.  }   

50.    

Reflection-通过annotation类取得注释-Java源码

 

通过annotation类取得注释

1.     import java.lang.annotation.Retention;   

2.     import java.lang.annotation.RetentionPolicy;  

3.     import java.lang.reflect.Method;   

4.       

5.     @Retention(RetentionPolicy.RUNTIME)   

6.     @interface MyAnno {   

7.       String str();  

8.       

9.       int val();   

10.  }   

11.    

12.  class Meta {  

13.    @MyAnno(str = "Two Parameters", val = 19)   

14.    public static void myMeth(String str, int i) {   

15.      Meta ob = new Meta();  

16.    

17.      try {   

18.        Class c = ob.getClass();  

19.    

20.        Method m = c.getMethod("myMeth", String.classint.class);   

21.    

22.        MyAnno anno = m.getAnnotation(MyAnno.class);   

23.    

24.        System.out.println(anno.str() + " " + anno.val());   

25.      } catch (NoSuchMethodException exc) {  

26.        System.out.println("Method Not Found.");   

27.      }   

28.    }   

29.    

30.    public static void main(String args[]) {  

31.      myMeth("test"10);   

32.    }   

33.  }   

34.    

Reflection-使用反射来显示注释的方法-Java源码

 

1.     import java.lang.annotation.Retention;   

2.     import java.lang.annotation.RetentionPolicy;  

3.     import java.lang.reflect.Method;   

4.       

5.     @Retention(RetentionPolicy.RUNTIME)   

6.     @interface MyAnno {   

7.       String str();  

8.       

9.       int val();   

10.  }   

11.    

12.  class Meta {  

13.    

14.    @MyAnno(str = "Annotation Example", val = 100)   

15.    public static void myMeth() {   

16.      Meta ob = new Meta();  

17.    

18.      try {   

19.        Class c = ob.getClass();  

20.    

21.        Method m = c.getMethod("myMeth");   

22.    

23.        MyAnno anno = m.getAnnotation(MyAnno.class);   

24.    

25.        System.out.println(anno.str() + " " + anno.val());   

26.      } catch (NoSuchMethodException exc) {  

27.        System.out.println("Method Not Found.");   

28.      }   

29.    }   

30.    

31.    public static void main(String args[]) {  

32.      myMeth();  

33.    }   

34.  }   

35.    

java反射

ReflectionJava被视为动态(或准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等等)、superclass(例如Object)、实现之interfaces(例如Cloneable),也包括fieldsmethods的所有信息,并可于运行时改变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<ma.length;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<fds.length;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.   }  



Java代码 

1.      package cn.IpUtils;  

2.        

3.      public class IpBean {  

4.          private String from; // IP段起始  

5.          private String to; // IP结束  

6.          private String position; // 地理名称      

7.          private int id = 0;  

8.        

9.          public String getFrom() {  

10.          return from;  

11.      }  

12.    

13.      public void setFrom(String from) {  

14.          this.from = from;  

15.      }  

16.    

17.      public String getTo() {  

18.          return to;  

19.      }  

20.    

21.      public void setTo(String to) {  

22.          this.to = to;  

23.      }  

24.    

25.      public String getPosition() {  

26.          return position;  

27.      }  

28.    

29.      public void setPosition(String position) {  

30.          this.position = position;  

31.      }  

32.    

33.      public int getId() {  

34.          return id;  

35.      }  

36.    

37.      public void setId(int id) {  

38.          this.id = id;  

39.      }  

40.    

41.        

42.  }  

 

 

原创粉丝点击