Java反射

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest
{
    public static void main(String[] args) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            ClassNotFoundException
    {
        
        Foo foo = new Foo("1254");
        Class aClass = foo.getClass();
        //打印所有的方法名
        Method[] methods = aClass.getMethods();
        for (int i = 0; i < methods.length; i++)
        {
            System.out.println("i=" + i + " " + methods[i].getName());
        }
        
        //得到某个非静态的隐藏方法
        Method aMethod = null;//aClass.getMethod("getID", null);
        aMethod = aClass.getDeclaredMethod("getID", null);
        //私有方法需要设置
        aMethod.setAccessible(true);
        String result = "";
        result = (String) (aMethod.invoke(foo, null));//参数中需要类对象
        System.out.println("user id is " + result);
        
        Method argsMethod = aClass.getMethod("setID",
                new Class[] { String.class });
        argsMethod.invoke(foo, new Object[] { "879" });
        result = (String) (aMethod.invoke(foo, null));//参数中需要类对象
        System.out.println("after setID user id is " + result);
        
        //得到某个静态的隐藏方法
        Class aClassForStaticMethod = Class.forName("Foo");
        Method staticMethod = aClassForStaticMethod.getMethod("getUserID", null);
        int intResult = (Integer) (staticMethod.invoke(null, null));//参数中不需要实例对象
        System.out.println("intResult is " + intResult);
        
        //得到所有的内部类
        Class[] classes = aClassForStaticMethod.getClasses();
        for (int i = 0; i < classes.length; i++)
        {
            System.out.println("i=" + i + " class name is "
                    + classes[i].getName());
        }
    }
    
}

class Foo
{
    private String id;
    
    public Foo(String aID)
    {
        id = aID;
    }
    
    ///** @hide */
    private String getID()
    {
        return id;
    }
    
    /** @hide */
    public void setID(String aId)
    {
        this.id = aId;
    }
    
    /** @hide */
    public static int getUserID()
    {
        return 100;
    }
    
    ///** @hide */
    private static class InnerClass
    {
        public String getInnerClassString()
        {
            return ";lkdjtgpowei";
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值