Java反射

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

下面将通过反射获取类的信息

person类

public class PersonBean {

    private String Name;
    private int age;
    private double price;
    private boolean isMarry;
    protected String mobile;
    public String address;

    public void setIsMarry(boolean isMarry) {
        this.isMarry = isMarry;
    }

    public boolean isMarry() {

        return isMarry;
    }

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

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

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public void setName(String name) {
        Name = name;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getAddress() {

        return address;
    }

    public int getAge() {
        return age;
    }

    public String getMobile() {
        return mobile;
    }

    public String getName() {
        return Name;
    }

    public double getPrice() {
        return price;
    }
}

反射获取相关代码:

public class Test {

    public static void main(String[] args) {
        System.out.println();
        System.out.println("setField:");
        setField();

        System.out.println();
        System.out.println("getFields:");
        getFields();

        System.out.println();
        System.out.println("invokeMethod:");
        invokeMethod();

        System.out.println();
        System.out.println("getMethod:");
        getMethod();

    }

    /**
     * 调用方法
     */
    private static void invokeMethod() {
        Class clazz = getClass(PersonBean.class.getName());

        try {
            Object object = clazz.newInstance();
            System.out.println("age is :"+ (((PersonBean)object).getAge()));
            Method method = clazz.getMethod("setAge", int.class);
            method.invoke(object, 123456);

            Method method1 = clazz.getMethod("getAge");
            int age = (int) method1.invoke(object);
            System.out.println("age is :"+ age);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置属性
     */
    private static void setField() {
        Class clazz = getClass(PersonBean.class.getName());
        try {
            PersonBean personBean = (PersonBean) clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();

            System.out.println("设置属性:");
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                field.setAccessible(true);
                if (field.getType().equals(int.class)) {
                    field.setInt(personBean, 24);

                } else if (field.getType().equals(double.class)) {
                    field.setDouble(personBean, 24);

                } else if (field.getType().equals(float.class)) {

                } else if (field.getType().equals(boolean.class)) {
                    field.setBoolean(personBean, true);

                } else if (field.getType().equals(String.class)) {
                    field.set(personBean, "广州");
                }

            }
            System.out.println(personBean.getAge());
            System.out.println(personBean.getAddress());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有属性
     */
    private static void getFields() {
        Class clazz = getClass(PersonBean.class.getName());
        Field[] fields = clazz.getDeclaredFields();

        System.out.println("属性有:");
        for (int i = 0; i < fields.length; i++) {
            System.out.println(Modifier.toString(fields[i].getModifiers())+" "+fields[i].getType().getSimpleName()+" "+fields[i].getName());
        }
    }

    private static String getModifiers(int modifiers) {
        String modifierName;
        Modifier modifier = new Modifier();
        if (modifier.isPublic(modifiers)) {
            modifierName = "public";
        } else if (modifier.isProtected(modifiers)) {
            modifierName = "protected";
        } else if (modifier.isPrivate(modifiers)) {
            modifierName = "private";
        } else {
            modifierName = modifiers+"";
        }
        return modifierName;
    }

    /**
     * 获取所有方法
     */
    private static void getMethod() {
        Class clazz = getClass(PersonBean.class.getName());
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method: methods) {
            String methodModifier = getModifiers(method.getModifiers());
            String methodName = method.getName();
            String methodReturnType = method.getReturnType().getName();
            Class<?>[] methodParam = method.getParameterTypes();

            String methodParamName = "";
            for (int i = 0; i < methodParam.length; i++) {
                Class param = methodParam[i];
                methodParamName = methodParamName + param.getName() + " arg"+i+",";
            }
            if (methodParamName.length() > 1) {
                methodParamName = methodParamName.substring(0, methodParamName.length()-1);
            }
            methodParamName = "("+methodParamName+")";

            System.out.println(methodModifier+" "+methodReturnType+" "+methodName +" "+methodParamName);
        }
    }

    /**
     * 获取class对象
     * @param clazzName
     * @return
     */
    private static Class getClass(String clazzName) {
        Class clazz = null;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return clazz;
    }

}

输出结果:

 

posted @ 2015-07-01 17:21  莫先生  阅读(687)  评论(1编辑  收藏  举报