Java反射初探

Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。
下面是jdk7的文档内容:

public Field getDeclaredField(String name)
                       throws NoSuchFieldException,
                              SecurityException

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object. The name parameter is a String that specifies the simple name of the desired field. Note that this method will not reflect the length field of an array class.
Parameters:
name - the name of the field
Returns:
the Field object for the specified field in this class
Throws:
NoSuchFieldException - if a field with the specified name is not found.
NullPointerException - if name is null
SecurityException - If a security manager, s, is present and any of the following conditions is met:
invocation of s.checkMemberAccess(this, Member.DECLARED) denies access to the declared field
the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
public final class Field
extends AccessibleObject
implements Member
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.
A Field permits widening conversions to occur during a get or set access operation, but throws an IllegalArgumentException if a narrowing conversion would occur.

public void set(Object obj,
       Object value)
         throws IllegalArgumentException,
                IllegalAccessException

Sets the field represented by this Field object on the specified object argument to the specified new value. The new value is automatically unwrapped if the underlying field has a primitive type.

public Object get(Object obj)
           throws IllegalArgumentException,
                  IllegalAccessException

Returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.
setAccessible是Field的父类AccesibleObject中方法

public void setAccessible(boolean flag)
                   throws SecurityException

Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress(禁止) Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.
First, if there is a security manager, its checkPermission method is called with a ReflectPermission(“suppressAccessChecks”) permission.

A SecurityException is raised if flag is true but accessibility of this object may not be changed (for example, if this element object is a Constructor object for the class Class).

A SecurityException is raised if this object is a Constructor object for the class java.lang.Class, and flag is true.
一段简单的代码:(设置私有属性的getter和setter方法)

import java.lang.reflect.Field;
public class ReflectHello{
    public static void main(String[] args)
    {
        String objstr = "BurningT.Hello";
        try {
            Class<?> cl = Class.forName(objstr);
            Object helloBean = cl.newInstance();

            Field[] helloA =    cl.getDeclaredFields();
            for (Field f1:helloA)
            {
                    f1.setAccessible(true);
                    System.out.println(f1.get(helloBean));
                    f1.set(helloBean, "123");
                    System.out.println(f1.get(helloBean));  
                    f1.setAccessible(false);
                    f1.set(helloBean,"123");
            }


        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

运行结果:
null
123
java.lang.IllegalAccessException: Class ReflectHello can not access a member of class BurningT.Hello with modifiers “private”
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
at java.lang.reflect.Field.doSecurityCheck(Field.java:959)
at java.lang.reflect.Field.getFieldAccessor(Field.java:896)
at java.lang.reflect.Field.set(Field.java:657)
at ReflectHello.main(ReflectHello.java:18)
method.invoke方法的返回值:
the result of dispatching the method represented by this object on obj with parameters args

来自google翻译
使用参数args在obj上调度此对象表示的方法的结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

helloworddm

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值