Java反射機制簡單瞭解_Reflection

反射機制:java

反射(Reflection)可以讓運行於JVM中的程序檢測和修改運行時的行爲。」這個概念經常會和內省(Introspection)混淆,如下是這兩個術語在Wikipedia中的解釋:ide

內省用於在運行時檢測某個對象的類型和其包含的屬性;函數

反射用於在運行時檢測和修改某個對象的結構及其行爲。this

從它們的定義能夠看出,內省是反射的一個子集。有些語言支持內省,但並不支持反射,如C++。spa


下面看反射的例子:code

Person.java對象

package reflect;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-7-10
 * Time: 下午2:10
 * To change this template use File | Settings | File Templates.
 */
public class Person {

    public static final int MAX_LENGTH = 10;
    public static final String BELONG = "MY";

    public int age;
    public String name;
    public String address;

    public Person() {
    }

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }


    public Person(int age, String name, String address) {
        this.age = age;
        this.name = name;
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }


    public void doWork(String command) {
        System.out.println("command==" + command);
    }

    public void doWork(String command, Boolean flag) {
        if (flag) {
            System.out.println("command==" + command);
        } else {
            System.out.println("command==" + command);
        }
    }


    public String sayHello() {
        return "I'm hello";
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;

        Person that = (Person) o;

        if (age != that.age) return false;
        if (!name.equals(that.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = age;
        result = 31 * result + name.hashCode();
        return result;
    }
}


ReflectionTest.javaip

package reflect;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;

/**
 * Created with IntelliJ IDEA.
 * User: ASUS
 * Date: 14-7-10
 * Time: 下午2:10
 * To change this template use File | Settings | File Templates.
 */
public class ReflectionTest {


    /**
     * 經過反正調用某個對象的方法
     *
     * @throws Exception
     */
    @Test
    public void test8() throws Exception {
        Person person = new Person();
        System.out.println(person.getClass().getName());


        Class<Person> personClass = (Class<Person>) Class.forName("reflect.Person");
        Person person1 = personClass.newInstance();
        System.out.println(person1.sayHello());


        /**
         * parameterTypes表示要調用函數的參數的class類型
         * 是一個可變參數列表
         * public Method getMethod(String name, Class<?>... parameterTypes)
         */

        try {
            Method doWorkMethod = personClass.getMethod("doWork", String.class);
            String command = "never give up";
            /**
             * invoke函數的第一個參數是一個類的實例,表示要調用該對象的方法,第二個及之後的參數是
             * 可變參數列表,表示要調用方法的參數
             */
            doWorkMethod.invoke(person1, command);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }


    /**
     * 獲取構造函數,並建立對象。
     */
    @Test
    public void test98() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Person> personClass = (Class<Person>) Class.forName("reflect.Person");

        Constructor<Person>[] constructors = (Constructor<Person>[]) personClass.getConstructors();

        int n = 0;
        for (Constructor constructor : constructors) {
            //構造函數的名字
            System.out.println(n + "=" + constructor.getName());
            //構造函數的參數的個數
            System.out.println(n + "=ParameterCount=" + constructor.getParameterCount());
            n++;
        }

        Person person = constructors[0].newInstance(12, "hello", "world");
        System.out.println(person.getName() + "     " + person.getAddress());

        Person person1 = constructors[1].newInstance(15, "sdsd");
        System.out.println(person1.getAge());
    }


    /**
     * 獲得某個類的全部屬性
     */
    @Test
    public void test987() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<Person> personClass = (Class<Person>) Class.forName("reflect.Person");

        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field.getName()); //字段的名稱
            System.out.println(field.getType().getName()); //字段的數據類型
            int modifiers = field.getModifiers();
            boolean isStatic = Modifier.isStatic(modifiers);
            if (isStatic) {
                /**
                 * 若是是靜態字段,get方法的參數能夠爲null
                 */
                System.out.println(field.getName() + "是靜態字段,value=" + field.get(null));
            } else {
                /**
                 * 若是是實例字段,obj對象是一個該實例字段所屬的對象或一個實例
                 */
                System.out.println(field.getName() + "不是靜態字段,value=" + field.get(personClass.newInstance()));
            }
        }
    }


    /**
     * 獲得一個類的全部方法
     */
    @Test
    public void test098() throws ClassNotFoundException {
        Class<Person> personClass = (Class<Person>) Class.forName("reflect.Person");
        Method[] methods = personClass.getMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
            int m = method.getModifiers();
            if (Modifier.isPublic(m)) {
                System.out.println(method.getName() + "是一個public方法");
            }

            Annotation[] annotations = method.getDeclaredAnnotations();
            System.out.println("===S===");
            for (Annotation annotation : annotations) {
                System.out.println(annotation.toString());
            }
            System.out.println("===E===");
        }
    }
}

====END====get

相關文章
相關標籤/搜索