Java SE之反射技术[Class,Field](一)

一、什么是反射?

  反射库(Reflection Library)提供了一个非常丰富且精心设计的工具集,以便编写能够动态操纵Java代码的程序。这项功能被大量地应用在JavaBeans中,它是Java组件的体系结构(有关Java Beans的详细内容见Java II卷)。使用反射,Java可以支持Visual Basic 用户习惯使用的工具。特别是再设计或运行中添加新类时,能够快速地应用开发工具动态地查询新添加类的能力。

  能够分析类能力的程序成为反射(Reflective)。反射机制的功能极其强大,在下面可以看到,反射机制可以用来:

  ①在运行中分析类的能力

  ②在运行中查看类对象,例如,编写一个toString()方法提供所有类使用

  ③实现通用数组操作代码

  ④利用Method对象,这个对象很像C++中的函数指针。

 

反射是一种功能强大且复杂的机制。使用它的主要人员是工具构造者,而不是应用程序员。

-----《Java核心技术卷 I 基础知识》

(手打)

 

二、引用的类与库

    库:java.lang.reflect.*

    类:

  ① Class [Java.lang.Class]

  ② Field [java.lang.reflect.Field]

    ③ Method  [java.lang.reflect.Method]

      ④ Constructor [java.lang.reflect.Constructor ]

      ⑤ Modifier [java.lang.reflect.Modifier]

      ⑥ AccessibleObject [java.lang.reflect.AccessibleObject]

 

三、常用方法总结

 

 

四、反射实例[测试]

 

 1 /**
 2  * @author:Johnny Zen
 3  * @date:2017-06-09
 4  * @description:一个实体类(Person)
 5  **/
 6 import java.lang.reflect.Field;
 7 
 8 import javax.activation.FileDataSource;
 9 
10 import com.sun.org.apache.bcel.internal.generic.NEW;
11 
12 public class Person extends Entity{
13     private String name;
14     private String password;
15     private String sex;
16     public String telephone;
17 
18     public Person() {
19         this.name = "测试名字:哇哈哈";
20         this.password = "测试密码:783234";
21         this.sex = "测试性别:男";
22         this.telephone = "测试电话:2947298569365";
23     }
24 
25     public Person(String name, String password, String sex, String telephone) {
26         super();
27         this.name = name;
28         this.password = password;
29         this.sex = sex;
30         this.telephone = telephone;
31     }
32 
33     public String getName() {
34         return name;
35     }
36 
37     public void setName(String name) {
38         this.name = name;
39     }
40 
41     public String getPassword() {
42         return password;
43     }
44 
45     public void setPassword(String password) {
46         this.password = password;
47     }
48 
49     public String getSex() {
50         return sex;
51     }
52 
53     public void setSex(String sex) {
54         this.sex = sex;
55     }
56 
57     public String getTelephone() {
58         return telephone;
59     }
60 
61     public void setTelephone(String telephone) {
62         this.telephone = telephone;
63     }
64     
65     @Override
66     public String toString() {
67         return "Person [name=" + name + ",  password=" + password + ", sex=" + sex + ",  telephone="
68                 + telephone + "]";
69     }
70 
71     
72 
73 }
74 
75 abstract class Entity{
76     
77 }

 

然后测试:

 

 1 public static void main(String args[]) throws IllegalAccessException{
 2          
 3          Person person1 = new Person("王华","123456","男","15902848904");
 4          Person person2 = new Person();
 5          Person person3 = new Person();
 6          try {
 7             System.out.println("对getClass()所有方法的遍历:"); 
 8             System.out.println("person1.getClass().desiredAssertionStatus():"+person1.getClass().desiredAssertionStatus()); //期望的断言状态
 9             
10             System.out.println("person1.getClass().equals(person2):"+person1.getClass().equals(person2));
11             System.out.println("person1.getClass().equals(person1):"+person1.getClass().equals(person1));
12             System.out.println("person2.getClass().equals(person3):"+person2.getClass().equals(person3));
13             
14             System.out.println("person1.getClass().getCanonicalName():"+person2.getClass().getCanonicalName());//获取权威正规的类名
15             
16             System.out.println("person1.getClass().getModifiers():"+person1.getClass().getModifiers());
17             System.out.println("person1.getClass().getName():"+person1.getClass().getName());
18             System.out.println("person1.getClass().getSimpleName():"+person1.getClass().getSimpleName());
19             System.out.println("person1.getClass().getTypeName():"+person1.getClass().getTypeName());
20             
21             System.out.println("person1.getClass().hashCode():"+person1.getClass().hashCode());//获取该类的hashcode值
22             System.out.println("person2.getClass().hashCode():"+person2.getClass().hashCode());
23             System.out.println("person3.getClass().hashCode():"+person3.getClass().hashCode());
24             
25             System.out.println("person1.getClass().toGenericString():"+person1.getClass().toGenericString());
26             System.out.println("person1.getClass().toString():"+person1.getClass().toString());
27             
28             System.out.println("person1.getClass().isAnnotation():"+person1.getClass().isAnnotation());  //是否为注解类型
29 //            System.out.println("【person1.getClass().asSubclass(null)】:"+person1.getClass().asSubclass(null));  //疑问?
30 //            System.out.println("【person1.getClass().cast(person1)】:"+person1.getClass().cast(person1));   //疑问?
31 //            System.out.println("person1.getClass().cast(person1):"+person1.getClass().cast(person1));   //疑问?
32 //            System.out.println("person1.getClass().isAnnotationPresent(null):"+person1.getClass().isAnnotationPresent(null)); //疑问?
33             
34             System.out.println("person1.getClass().isAnonymousClass():"+person1.getClass().isAnonymousClass()); //是否是匿名类
35             System.out.println("(new int[2]).getClass().isAnonymousClass():"+(new int[2]).getClass().isAnonymousClass()); //是否是匿名类
36             
37             System.out.println("person1.getClass().isArray():"+person1.getClass().isArray()); //是否是数组类
38             System.out.println("(new int[2]).getClass().isArray():"+(new int[2]).getClass().isArray()); //是否是数组类
39             
40             /*重点方法:getFields():*/
41             System.out.println("***************************************************************************************************");
42             System.out.println("person1.getClass().getFields()[0].getName():"+person1.getClass().getFields()[0].getName()); //获取公共属性的第(0+1)个属性
43         
44             Field fields1[] = person1.getClass().getFields(); //仅仅能获取到public属性的field
45 //            System.out.println("fields1[1].get(person2):"+fields1[1].get(person2)); //由于第二个域获取不到,域数组长度为1,故产生数组超界
46             Field fields2[] = person1.getClass().getDeclaredFields(); //获取到所有声明的field(包括private的)
47             System.out.println("fields2[1].get(person2):"+fields2[1].get(person2));
48             System.out.println("fields2[1].get(person1):"+fields2[1].get(person1));
49             
50             System.out.println("fields2[1].getName():"+fields2[1].getName());
51             System.out.println("fields2[1].hashCode():"+fields2[1].hashCode());
52             System.out.println("fields2[1].toString():"+fields2[1].toString());
53         
54             System.out.println("fields2[1].equals(person2):"+fields2[1].equals(person2));
55             System.out.println("fields2[1].equals(fields2[1]):"+fields2[1].equals(fields2[1]));//field是否相同
56         
57             System.out.println("fields2[1].getType():"+fields2[1].getType());

58        System.out.println("fields[1].getType().getSimpleName()"+fields[1].getType().getSimpleName());  
59 } catch (Exception e) { 60 e.printStackTrace(); 61 // TODO: handle exception 62 } 63 64 65 }

 

 

结果:

 1 对getClass()所有方法的遍历:
 2 person1.getClass().desiredAssertionStatus():false
 3 person1.getClass().equals(person2):false
 4 person1.getClass().equals(person1):false
 5 person2.getClass().equals(person3):false
 6 person1.getClass().getCanonicalName():Person
 7 person1.getClass().getModifiers():1
 8 person1.getClass().getName():Person
 9 person1.getClass().getSimpleName():Person
10 person1.getClass().getTypeName():Person
11 person1.getClass().hashCode():914424520
12 person2.getClass().hashCode():914424520
13 person3.getClass().hashCode():914424520
14 person1.getClass().toGenericString():public class Person
15 person1.getClass().toString():class Person
16 person1.getClass().isAnnotation():false
17 person1.getClass().isAnonymousClass():false
18 (new int[2]).getClass().isAnonymousClass():false
19 person1.getClass().isArray():false
20 (new int[2]).getClass().isArray():true
21 ***************************************************************************************************
22 person1.getClass().getFields()[0].getName():telephone
23 fields2[1].get(person2):测试密码:783234
24 fields2[1].get(person1):123456
25 fields2[1].getName():password
26 fields2[1].hashCode():-960414226
27 fields2[1].toString():private java.lang.String Person.password
28 fields2[1].equals(person2):false
29 fields2[1].equals(fields2[1]):true
30 fields2[1].getType():class java.lang.String
31 fields[1].getType().getSimpleName():String

 

补充:

    public static void main(String[] args) {
        // String.class.getCanonicalName() => java.lang.String | canonical 根据教规的,按照宗教法规的;真经的,正经的;标准的,典范的;准确的
        // String.class.getTypeName() => java.lang.String
        // String.class.getSimpleName() => String
        System.out.print(String.class.getSimpleName());
    }

  

 

 

五、参考文档

Java反射之Field用法

Java反射机制Class类的用法详解

Java核心技术之反射(详细API和MyBatis简单实现)

posted @ 2017-06-09 01:50  千千寰宇  阅读(363)  评论(0编辑  收藏  举报