• Java Method.invoke()方法具有什么功能


    转自:

      Java Method.invoke()方法具有什么功能

    下文讲述java中Method.invoke()方法的功能简介说明,如下所示:

    Method.invoke()方法的功能:
         通过反射运行指定的方法
    

    Method.invoke()方法的语法

    public native Object invoke(Object receiver, Object... args) 
    throws IllegalAccessException, IllegalArgumentException, InvocationTargetException;
    参数说明
       第一个参数是方法属于的对象(如果是静态方法,则可以直接传 null)
       第二个可变参数是该方法的参数
    返回值:
    Object
    异常:
      当调用的方法有抛出异常,异常会被 java.lang.reflect.InvocationTargetException
    

    例:

    package com.java265.other;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Method;
    public class TestClass {
    	public static void main(String[] args) throws Exception {
    		Class clazz = Class.forName("com.java265.other.User");
    		Method method = clazz.getDeclaredMethod("setAge", int.class);
    		method.setAccessible(true);
    		Constructor c = clazz.getConstructor();
    		User u = (User) c.newInstance();
    		method.invoke(u, 78);
    		System.out.println(u.getAge());
    		}
    }
    class User {
    	private int age;
    	public User() {
    	}
    	public int getAge() {
    		return this.age;
    	}
    	private void setAge(int age) {
    		this.age = age;
    	}
    }
    -----运行以上代码,将输出以下信息----
    78
  • 相关阅读:
    【数据结构】哈希表
    LeetCode 69. x 的平方根
    设计模式(4)-行为型模式
    OpenCV在Windows系统上安装编译
    鸿蒙 API9 接入 Crypto库
    教你30分钟快速搭建直播间
    数据库.创建表
    Python文件夹遍历
    使用curl执行Http请求
    adb突然获取不到华为/荣耀手机。。。
  • 原文地址:https://blog.csdn.net/qq_25073223/article/details/126136532