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
经验分享 程序员 微信小程序 职场和发展