`
凯旋人生
  • 浏览: 61730 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

JAVA的反射机制Reflection

    博客分类:
  • JAVA
阅读更多

Java的反色机制是运行时的环境。

Reflection是java被视为(准)动态语言的关键,它允许程序在运行时透过Reflection APIs取得任一个已知名称的类的内部信息。包括modifiers(诸如public,static等等)、superclass(如Object)等,实现的interfaces(如Serializable),也包括fields和methods所有信息,并可以在运行时改变fields内容和调用methods。java这种看透class的能力(the ability of the program to examine itself)被成为introspection(内省)。

反射可以做到:
在运行是判断任意一个对象所属的类。
在运行时构造任意一个类的对象。
在运行时判断任意一个类所具有的对象和方法。
在运行时调用任意一个对象的方法。

java.lang.reflect包

Class类:代表一个类。
Field: 代表成员变量。(成员变量也称为类的属性)。
Method:代表类的方法。
Constructor:代表类的够造方法。
Array类:提供了动态创建数组,以及访问数组元素的方法。

getName():获得类的完整的名字。
getFields():获得类的public类型属性的
getDeclaredFields():获得类的所有属性
getMethods();获得类的public类型方法
getDeclaredMethods():获得类所有方法
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的不带参数的构造方法创建这个类的一个对象

public class DumpMethods  {
    public static void main(String[] args)throws Exception {
        Class<?> classType = Class.forName(“java.lang.String”);
        Method methods[] =classType.getDeclaredMethods();
        for(Method m: methods)
        {
            System.out.println(m.toString());
        }
    }
}

**********************************************************

例1:

package com.langsin.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTester {
    public Object copy(Object object)throws Exception
    {
        // 获得对象的类型
        Class<?> classType = object.getClass();
        System.out.println("Class:"+classType.getName());
        // 通过默认构造方法创建一个新的对象
        Object objectCopy= classType.getConstructor(new Class[]{}).newInstance(new Object[]{});

        // 获得对象的所有属性
        Field fields[] = classType.getDeclaredFields();
        for(Field field: fields)
        {
            String fieldName = field.getName();
            String firstLetter =fieldName.substring(0,1).toUpperCase();
            // 获得和属性对应的getXXX()方法的名字
            String getMethodName= "get"+firstLetter+fieldName.substring(1);
            // 获得和属性对应的setXXX()方法的名字
            String setMethodName= "set"+firstLetter+fieldName.substring(1);
            // 获得和属性对应的getXXX()方法
            Method getMethod = classType.getMethod(getMethodName,new Class[]{});
            // 获得和属性对应的setXXX()方法
            Method setMethod = classType.getMethod(setMethodName,new Class[]{field.getType()});

            // 调用原对象的getXXX()方法
            Object value = getMethod.invoke(object,new Class[]{});
            System.out.println(fieldName + ":" + value);
            // 调用拷贝对象的setXXX()方法
            setMethod.invoke(objectCopy, new Object[]{value});
        }
        return objectCopy;
    }
    /**
     * @param args
     */
    public static void main(String[] args)throws Exception {
         Customer customer = new Customer("Tom", 21);
         customer.setId(new Long(1));
         Customer customerCopy =(Customer)new ReflectTester().copy(customer);
         System.out.println("Copy information:" + customerCopy.getId() + " " + customerCopy.getName() + " "
                    + customerCopy.getAge());
    }
}

class Customer
{
    private Long id;
    private String name;
    private int age;
    public Customer() {
    }
    public Customer( String name, int age) {
        this.name = name;
        this.age = age;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

**************************************

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics