谈谈Java的反射机制

在Java语言,有一大特性,就是反射机制.依靠这套机制,有了很多很好的应用,比如stucts, hibernate, spring等等.

那什么叫反射呢?
它允许运行中的 Java 程序对自身进行检查,或者说“自审”,并能直接操作程序的内部属性。(注意是在运行中,不是在编译中)。
反射的核心类是Class。围绕着这个核心类,Member,Field, Method,Constructor等一些类是反射的基本骨架。有了这些类的支持,在程序的运行过程中,我们可以动态的创建对象,动态的去调用方法,而不是仅限于在编译时候,这一点很有价值。

import java.io.PrintStream;
import java.lang.reflect.*;

class Person {
    public int age;

    public String hairColor;

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

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

public class ReflectionTest {

    private static PrintStream out = System.out;

    /**
     * This method is used to get public fields of an instanced object.
     * Note: cannot get private fields
     * Key method: (Field) get()
     */
    public static Object getProperty(Object obj, String fieldName) throws Exception {    
        Class ownerClass = obj.getClass();
        Field field = ownerClass.getField(fieldName);
        Object property = field.get(obj);

        return property;
    }

    /**
     * This method is used to set public fields of an instanced object.
     * Note: cannot set private fields
     * Key method: (Field) set()
     */
    public static void setProperty(Object obj, String fieldName, Object newValue) throws Exception {
        Class objClass = obj.getClass();
        Field field = objClass.getField(fieldName);
        field.set(obj, newValue);
    }

    /**
     * This method is used to initialize an object.
     * Key method: (Constructor) newInstance()
     */
    public static Object newInstance(String className, Object ... parameter) throws Exception {
        Class cls = Class.forName(className);

        int pLength = parameter.length;
        Class parameterTypes[] = new Class[pLength];
        Constructor ctorlist[] = cls.getDeclaredConstructors();
        parameterTypes = ctorlist[0].getParameterTypes();
        Constructor con = cls.getConstructor(parameterTypes);
        Object argList[] = new Object[pLength];
        for (int i = 0; i < pLength; i++) {
            argList[i] = parameter[i];
        }

        return con.newInstance(argList);
    }

    /**
     * This method is used to invoke a method.
     * Key method: (Method) invoke()
     */
    public static Object invokeMethod(Object obj, String methodName, Object arg[]) throws Exception {
        Class cls = obj.getClass();

        int pLength = arg.length;
        Class[] parameterTypes = new Class[pLength];
        parameterTypes[0] = int.class;
        Method method = cls.getMethod(methodName, parameterTypes);

        return method.invoke(obj, arg);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值