(转)Java.lang.reflect.Method invoke方法 实例

背景:今天在项目中用到Method 的invoke方法,但是并不理解,查完才知道,原来如此!

import java.lang.reflect.Method;  

/**
 * Java.lang.reflect.Method invoke方法 实例
 * 程序中配置文件中有对实体对象的get,set方法的描述,通过应用invoke()方法调用实体对象的method方法 return
 * m_oGetter.invoke(oSrc, null); oSrc为实体对象,Method m_oGetter
 * 这里的m_oGetter是对应于在代理实例(oSrc)上调用的接口方法的 Method 实例,下面参考示例代码
 * 

 */  

class Employee {
    // 定义一个员工类
    public Employee() {
        age = 0;
        name = null;
    }  

    // 将要被调用的方法
    public void setAge(int a) {
        age = a;
    }  

    // 将要被调用的方法
    public int getAge() {
        return age;
    }  

    // 将要被调用的方法
    public void printName(String n) {
        name = n;
        System.out.println("The Employee Name is: " + name);
    }  

    private int age;
    private String name;
}  

public class InvokeMethods {  

    public static void main(String[] args) {  

        Employee emp = new Employee();
        Class<?> cl = emp.getClass();
        // /getClass获得emp对象所属的类型的对象,Class就是类的类
        // /Class是专门用来描述类的类,比如描述某个类有那些字段,
        // /方法,构造器等等!
        try {  

            // /getMethod方法第一个参数指定一个需要调用的方法名称
            // /这里是Employee类的setAge方法,第二个参数是需要调用
            // 方法的参数类型列表,是参数类型!如无参数可以指定null
            // /该方法返回一个方法对象
            Method sAge = cl.getMethod("setAge", new Class[] { int.class });
            Method gAge = cl.getMethod("getAge", null);
            Method pName = cl.getMethod("printName",
                    new Class[] { String.class });
            /** *使用invoke调用指定的方法 */
            Object[] args1 = { new Integer(25) };
            // 参数列表
            // emp为隐式参数该方法不是静态方法必须指定
            sAge.invoke(emp, args1);
            Integer AGE = (Integer) gAge.invoke(emp, null);
            int age = AGE.intValue();
            System.out.println("The Employee Age is: " + age);
            Object[] args3 = { new String("Jack") };
            pName.invoke(emp, args3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }  

}  

运行结果:

The Employee Age is: 25
The Employee Name is: Jack

时间: 2024-08-09 06:23:18

(转)Java.lang.reflect.Method invoke方法 实例的相关文章

java.lang.reflect.Method.getAnnotation()方法示例【通过反射获取到方法对象再获取方法对象上的注解信息】

转: java.lang.reflect.Method.getAnnotation()方法示例 java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)方法如果存在这样的注释,则返回指定类型的元素的注释,否则为null. 声明 以下是java.lang.reflect.Method.getAnnotation(Class <T> annotationClass)方法的声明. public <T exte

java.lang.reflect.Method

java.lang.reflect.Method 一.Method类是什么 Method是一个类,位于java.lang.reflect包下. 在Java反射中 Method类描述的是 类的方法信息,通俗来讲 有一个类如下: 1 package com.testReflect; 2 3 public class MethodDemo { 4 private int num = 2; 5 private String str = "xixi"; 6 7 public int addRes

Hadoop中RPC协议小例子报错java.lang.reflect.UndeclaredThrowableException解决方法

最近在学习传智播客吴超老师的Hadoop视频,里面他在讲解RPC通信原理的过程中给了一个RPC的小例子,但是自己编写的过程中遇到一个小错误,整理如下: log4j:WARN No appenders could be found for logger (org.apache.hadoop.metrics2.lib.MutableMetricsFactory).log4j:WARN Please initialize the log4j system properly.log4j:WARN See

错误: java.lang.reflect.InvocationTargetException

错误: java.lang.reflect.InvocationTargetException    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 

Cglib学习报错 java.lang.reflect.InvocationTargetException--&gt;null

package javacore.testForCglibProxy; import java.lang.reflect.Method; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class GetNewBook { public static void main(String[] ar

json解析异常 - net.sf.json.JSONException: java.lang.reflect.InvocationTargetException

注:在项目中, 我使用原生的ajax请求数据的时候, JSONObject没能帮我解析, 当却不给我报错, 我是在junit单元测试中测试的时候, 发现的.发现好多时候, 特别是通过ajax请求, 不给我们报错,很郁闷, 特别是ie, 有些问题, 得借助FireFox的返回结果分析. 当然, FireFox有时也没报错. 异常栈: net.sf.json.JSONException: java.lang.reflect.InvocationTargetException at net.sf.js

mavne install 报错org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.InvocationTargetException

maven install 报错 org.apache.maven.surefire.util.SurefireReflectionException: java.lang.reflect.InvocationTargetException; nested exception is java.lang.reflect.InvocationTargetException: nulljava.lang.reflect.InvocationTargetException at sun.reflect.

SpringBoot项目启动报错:java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

.   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Sprin

java.lang.reflect.InvocationHandler中invoke()方法调用时机

Java中动态代理的实现,关键就是这两个东西:Proxy.InvocationHandler,下面从InvocationHandler接口中的invoke方法入手,简单说明一下Java如何实现动态代理的. invoke方法的完整形式如下: public Object invoke(Object proxy, Method method, Object[] args) throws Throwable       {              method.invoke(obj, args);