反射

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。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值