反射

来源:互联网 发布:淘宝详情页模板下载 编辑:程序博客网 时间:2024/06/05 15:53

1 获取字段值

package com.reflect;import java.lang.reflect.Field;public class Reflect {public static void main(String[] args){try {Class cl = Class.forName("com.reflect.Test");Object test = cl.newInstance();Field name = cl.getField("name");Field age = cl.getField("age");System.out.println(name.get(null));System.out.println(age.get(test));} catch (Exception e) {}}}

public class Test {public static String name = "lily";public int age = 3;}
/**     * Returns the value of the field in the specified object. This reproduces     * the effect of {@code object.fieldName}     *     * <p>If the type of this field is a primitive type, the field value is     * automatically boxed.     *     * <p>If this field is static, the object argument is ignored.     * Otherwise, if the object is null, a NullPointerException is thrown. If     * the object is not an instance of the declaring class of the method, an     * IllegalArgumentException is thrown.     *     * <p>If this Field object is enforcing access control (see AccessibleObject)     * and this field is not accessible from the current context, an     * IllegalAccessException is thrown.     *     * @param object     *            the object to access     * @return the field value, possibly boxed     * @throws NullPointerException     *             if the object is {@code null} and the field is non-static     * @throws IllegalArgumentException     *             if the object is not compatible with the declaring class     * @throws IllegalAccessException     *             if this field is not accessible     */    public Object get(Object object) throws IllegalAccessException, IllegalArgumentException {        return getField(object, declaringClass, type, slot, flag);    }
这个方法可以得到指定的对象的字段值。

如果字段是基本数据类型,返回的值会自动装箱。

如果字段是static类型,object可以为null(static类型的字段是类变量),如果不是static,则必须指定object。





0 0
原创粉丝点击