JAVA 反射


 

 

 

 

Method

getDeclaredMethod/getMethod

getDeclaredMethod:此 Class 对象所表示的类自身所有的方法

getMethod :Class 对象所表示的类或接口(包括父类)的指定公共成员方法

 

Method invoke(Object obj,Object args[])

 

 

Field

getDeclaredField/ getField

 

 

fields.get(object)

fields.set(object)

 

 

Class

Class cls = Class.forName("com.rain.B")

 

 

 

 

 

 



package com.example.lenvov.com.utils;

/**
 * Created by lenvov on 2017/3/2.
 */
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Title: 私有方法调用工具类
 * Description:利用java反射调用类的的私有方法
 * Copyright: Copyright (c) 2007
 * @author huqs
 */
public class PrivateUtil {
    /**
     * 利用递归找一个类的指定方法,如果找不到,去父亲里面找直到最上层Object对象为止。
     *
     * @param clazz      目标类
     * @param methodName 方法名
     * @param classes    方法参数类型数组
     * @return 方法对象
     * @throws Exception
     */
    public static Method getMethod(Class clazz, String methodName,
                                   final Class[] classes) throws Exception {
        Method method = null;
        try {
            method = clazz.getDeclaredMethod(methodName, classes);
        } catch (NoSuchMethodException e) {
            try {
                method = clazz.getMethod(methodName, classes);
            } catch (NoSuchMethodException ex) {
                if (clazz.getSuperclass() == null) {
                    return method;
                } else {
                    method = getMethod(clazz.getSuperclass(), methodName,
                            classes);
                }
            }
        }
        return method;
    }

    /**
     * @param obj        调整方法的对象
     * @param methodName 方法名
     * @param classes    参数类型数组
     * @param objects    参数数组
     * @return 方法的返回值
     */
    public static Object invoke(final Object obj, final String methodName,
                                final Class[] classes, final Object[] objects) {
        try {
            Method method = getMethod(obj.getClass(), methodName, classes);
            if (method == null) return null;

            method.setAccessible(true);// 调用private方法的关键一句话
            return method.invoke(obj, objects);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Object invoke(final Object obj, final String methodName,
                                final Class[] classes) {
        return invoke(obj, methodName, classes, new Object[]{});
    }

    public static Object invoke(final Object obj, final String methodName) {
        return invoke(obj, methodName, new Class[]{}, new Object[]{});
    }

    //
// /**
//  * 测试反射调用
//  *
//  * @param args
//  */
    public static void main(String[] args) {
        //PrivateUtil.invoke(new B(), "printlnA", new Class[] { String.class },
        // new Object[] { "test"});

     PrivateUtil.invoke(new A(), "test1", new Class[] { String.class,int.class },
                new Object[] { "test",5});


      //  PrivateUtil.invokeMethod(new A(), "test1", new Object[]{"test", (int)5});
        //PrivateUtil.invoke(new B(), "printlnB");
    }

    // 利用递归找一个类的指定方法,如果找不到,去父亲里面找直到最上层Object对象为止。

    /**
     * 反射调用方法
     *
     * @param newObj     实例化的一个对象
     * @param methodName 对象的方法名
     * @param args       参数数组
     * @return 返回值
     * @throws Exception
     */
    public static Object invokeMethod(Object newObj, String methodName, Object[] args) {
        Class ownerClass = newObj.getClass();
        Class[] argsClass = new Class[args.length];
        for (int i = 0, j = args.length; i < j; i++) {
            argsClass[i] = args[i].getClass();
        }

        Method method = null;
        try {
            method = ownerClass.getDeclaredMethod(methodName, argsClass);
        } catch (NoSuchMethodException e) {
            System.out.print("no such method ---" + methodName);
        }

        if (method != null) {
            method.setAccessible(true);
            try {
                return method.invoke(newObj, args);
            } catch (Exception E) {
                System.out.print("invoke exception ---" + methodName);
            }
            return null;
        } else {
            return null;
        }

    }

}

class A {
   private void printlnA(String s) {
      System.out.println(s);
   }

    private void test1(String s,int i) {
        System.out.println("s="+s+"; i="+i);
    }
}

class B extends A {
   private void printlnB() {
      System.out.println("b");
   }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值