读书人

Java 反照与内省

发布时间: 2012-12-25 16:18:29 作者: rapoo

Java 反射与内省

一、java反射机制
JAVA反射机制是在运行状态中,
对于任意一个类,都能够得到这个类的所有属性和方法;
对于任意一个对象,都能够调用它的任意一个方法;
这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制.

概括一下:
反射就是让你可以通过名称来得到对象(类,属性,方法)的技术。
例如我们可以通过类名来生成一个类的实例;
知道了方法名,就可以调用这个方法;
知道了属性名就可以访问这个属性的值。

1、获取类对应的Class对象
?? 运用(已知对象)getClass():Object类中的方法,每个类都拥有此方法。
?? 如: String str = new String();
Class strClass = str.getClass();
?? 运用(已知子类的class) Class.getSuperclass():Class类中的方法,返回该Class的父类的Class;
?? 运用(已知类全名):Class.forName() 静态方法
?? 运用(已知类): 类名.class

2、通过类名来构造一个类的实例
?? a、调用无参的构造函数:
?? Class newoneClass = Class.forName(类全名);
?? newoneClass.newInstance();

?? b、调用有参的构造函数:我们可以自定义一个函数。
?? public Object newInstance(String className, Object[] args) throws Exception {
?? //args为参数数组
?? Class newoneClass = Class.forName(className);
?? //得到参数的Class数组(每个参数的class组成的数组),由此来决定调用那个构造函数
?? Class[] argsClass = new Class[args.length];
?? for (int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
?? }
?? Constructor cons = newoneClass.getConstructor(argsClass); //根据argsClass选择函数
?? return cons.newInstance(args); //根据具体参数实例化对象。
?? }

3、得到某个对象的属性

?? a、非静态属性:首先得到class,然后得到这个class具有的field,然后以具体实例为参数调用这个field

?? public Object getProperty(Object owner, String fieldName) throws Exception {
?????? Class ownerClass = owner.getClass();//首先得到class
?????? Field field = ownerClass.getField(fieldName);
?????? //然后得到这个class具有的field,也可以通过getFields()得到所有的field
?????? Object property = field.get(owner);
?????? //owner指出了取得那个实例的这个属性值,如果这个属性是非公有的,这里会报IllegalAccessException。
?????? return property;

?? }

?? b、静态属性:
????? 只有最后一步不同,由于静态属性属于这个类,所以只要在这个类上调用这个field即可
????? Object property = field.get(ownerClass);

4、执行某对象的方法

? public Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception {
???? Class ownerClass = owner.getClass(); //也是从class开始的
???? //得到参数的class数组,相当于得到参数列表的类型数组,来取决我们选择哪个函数。
???? Class[] argsClass = new Class[args.length];
???? for (int i = 0, j = args.length; i < j; i++) {
???????? argsClass[i] = args[i].getClass();
???? }
???? //根据函数名和函数类型来选择函数
???? Method method = ownerClass.getMethod(methodName, argsClass);
???? return method.invoke(owner, args);//具体实例下,具体参数值下调用此函数
? }

5、执行类的静态方法
?? 和上面的相似只是最后一行不需要指定具体实例
?? return method.invoke(null, args);

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

?? public boolean isInstance(Object obj, Class cls) {
??????? return cls.isInstance(obj);
?? }

测试bean类:SimpleBean.java

?Java 反照与内省
    package com.royzhou.bean;public class SimpleBean {private String name;private String[] hobby;public SimpleBean() {}public SimpleBean(String name, String[] hobby) {this.name = name;this.hobby = hobby;}public void setName(String name) {this.name = name;}public String getName() {return this.name;}public void setHobby(String[] hobby) {this.hobby = hobby;}public String[] getHobby() {return this.hobby;}public String toString() {String returnValue = super.toString() + "\n";returnValue += "name:=" + this.name + "\n";if(this.hobby != null) {returnValue += "hobby:";for(String s : this.hobby) {returnValue += s + ",";}returnValue += "\n";}return returnValue;}}



    反射测试类:ReflectTest.java

    ?Java 反照与内省
      package com.royzhou.bean;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;public class ReflectTest {public static void main(String[] args) throws Exception {Class clazz = SimpleBean.class;//使用无参构造函数实例化beanSimpleBean sb = (SimpleBean)clazz.newInstance();System.out.println(sb);//使用有参构造函数实例化beanConstructor constructor = clazz.getConstructor(new Class[]{String.class, String[].class});sb = (SimpleBean)constructor.newInstance(new Object[]{"royzhou",new String[]{"football","basketball"}});System.out.println(sb);//为name字段设置值Field field = clazz.getDeclaredField("name");field.setAccessible(true); //避免private不可访问抛出异常field.set(sb, "royzhou1985");System.out.println("modify name using Field:=" + sb.getName() + "\n");//列出类SimpleBean的所有方法Method[] methods = clazz.getDeclaredMethods();System.out.println("get methods of class SimpleBean:");for(Method method : methods) {if("setHobby".equals(method.getName())) {//动态调用类的方法来为hobby设置值method.invoke(sb, new Object[]{new String[]{"tennis","fishing"}});}System.out.println(method.getName());}System.out.println("\nset by invoke Method");System.out.println(sb);}}



      输出结果:
      com.royzhou.bean.SimpleBean@757aef
      name:=null

      com.royzhou.bean.SimpleBean@d9f9c3
      name:=royzhou
      hobby:football,basketball,

      modify name using Field:=royzhou1985

      get methods of class SimpleBean:
      setHobby
      getHobby
      getName
      toString
      setName

      set by invoke Method
      com.royzhou.bean.SimpleBean@d9f9c3
      name:=royzhou1985
      hobby:tennis,fishing,


      二、java内省机制

      ??? 内省是 Java 语言对 Bean 类属性、事件的一种处理方法(也就是说给定一个javabean对象,我们就可以得到/调用它的所有的get/set方法)。
      ??? 例如类 A 中有属性 name, 那我们可以通过 getName,setName 来得到其值或者设置新的值。通过 getName/setName 来访问 name 属性,这就是默认的规则。
      ??? Java 中提供了一套 API 用来访问某个属性的 getter/setter 方法,通过这些 API 可以使你不需要了解这个规则,这些 API 存放于包 java.beans 中。
      ??? 一般的做法是通过类 Introspector 的 getBeanInfo方法 来获取某个对象的 BeanInfo 信息,然后通过 BeanInfo 来获取属性的描述器(PropertyDescriptor),
      ??? 通过这个属性描述器就可以获取某个属性对应的 getter/setter 方法,然后我们就可以通过反射机制来调用这些方法。
      ??
      内省测试类:Introspector.java

      ?Java 反照与内省
        package com.royzhou.bean;import java.beans.BeanInfo;import java.beans.Introspector;import java.beans.MethodDescriptor;import java.beans.PropertyDescriptor;public class IntrospectorTest {public static void main(String[] args) throws Exception {SimpleBean sb = new SimpleBean("royzhou",new String[]{"football","backetball"});System.out.println(sb);/** * 使用Introspector.getBeanInfo(SimpleBean.class)将Bean的属性放入到BeanInfo中。 * 第二个参数为截止参数,表示截止到此类之前,不包括此类。 * 如果不设置的话,那么将会得到本类以及其所有父类的info。 * BeanInfo中包含了SimpleBean的信息 */BeanInfo beanInfo = Introspector.getBeanInfo(sb.getClass());//将每个属性的信息封装到一个PropertyDescriptor形成一个数组其中包括属性名字,读写方法,属性的类型等等PropertyDescriptor[] propertys = beanInfo.getPropertyDescriptors();for(PropertyDescriptor property : propertys) {System.out.println("属性名:" + property.getName());System.out.println("类型:" + property.getPropertyType());}System.out.println();System.out.println("列出SimpleBean的所有方法");MethodDescriptor[] methods = beanInfo.getMethodDescriptors();for(MethodDescriptor method : methods) {System.out.println(method.getName());}System.out.println();/** * 重新设置属性值 */for(PropertyDescriptor property : propertys) {if(property.getPropertyType().isArray()){ //getPropertyType得到属性类型。if(property.getPropertyType().isArray()) {if("hobby".equals(property.getName())) {//getComponentType()可以得到数组类型的元素类型if(property.getPropertyType().getComponentType().equals(String.class)) {//getWriteMethod()得到此属性的set方法----Method对象,然后用invoke调用这个方法property.getWriteMethod().invoke(sb, new Object[]{new String[]{"tennis","fishing"}});}}} } else if("name".equals(property.getName())) {property.getWriteMethod().invoke(sb, new Object[] { "royzhou1985" }); }}/** * 获取对象的属性值 */System.out.println("获取对象的属性值");for(PropertyDescriptor property : propertys) {if(property.getPropertyType().isArray()){ //getPropertyType得到属性类型。 //getReadMethod()得到此属性的get方法----Method对象,然后用invoke调用这个方法 String[] result=(String[]) property.getReadMethod().invoke(sb, new Object[]{}); System.out.print(property.getName()+":");//getName得到属性名字 for (int j = 0; j < result.length; j++) { System.out.print(result[j] + ","); } System.out.println(); } else{ System.out.println(property.getName()+":"+property.getReadMethod().invoke(sb, new Object[]{})); }}}}



        输出结果:
        com.royzhou.bean.SimpleBean@757aef
        name:=royzhou
        hobby:football,backetball,

        属性名:class
        类型:class java.lang.Class
        属性名:hobby
        类型:class [Ljava.lang.String;
        属性名:name
        类型:class java.lang.String

        列出SimpleBean的所有方法
        hashCode
        setHobby
        equals
        wait
        wait
        notify
        getClass
        toString
        notifyAll
        getHobby
        setName
        wait
        getName

        获取对象的属性值
        class:class com.royzhou.bean.SimpleBean
        hobby:tennis,fishing,
        name:royzhou1985

        三、总结
        ??? 将 Java 的反射以及内省应用到程序设计中去可以大大的提供程序的智能化和可扩展性,有很多项目都是采取这两种技术来实现其核心功能,
        ??? 其实应该说几乎所有的项目都或多或少的采用这两种技术,在实际应用过程中二者要相互结合方能发挥真正的智能化以及高度可扩展性。

读书人网 >编程

热点推荐