Method.invoke()详解
时间: 2023-03-13 12:42:18 浏览: 186
Method.invoke() 是一个 Java 语言提供的反射 API,它允许在运行时调用任意一个对象的方法,不论该方法是否为 public、private、protected 或 package-private。它的原型方法是 Object.invoke(Object obj, Object... args),它可以接受任意多个参数,并在指定的对象上调用指定的方法,然后返回方法的返回值。
相关问题
method.invoke()
The method.invoke() method is a part of the Java Reflection API that is used to invoke a method dynamically at runtime. It is used to invoke a method on a specified object, passing any required arguments, and returning the result of the method call.
The syntax for method.invoke() is as follows:
Object result = method.invoke(object, args);
Here, "method" is the Method object that represents the method to be invoked, "object" is the object on which the method is to be invoked, and "args" is an array of arguments to be passed to the method.
The method.invoke() method can be used to call any method of an object at runtime, regardless of the access modifiers of the method. It is commonly used in situations where the method to be called is not known at compile-time, or when the method needs to be called dynamically based on user input or configuration data.
method.invoke
`method.invoke()`是Java中的反射机制方法之一,它可以在运行时动态地调用一个对象的方法。
具体来说,`method`是一个`Method`类的实例,代表一个方法。`invoke()`方法可以传入两个参数:第一个参数是要调用该方法的对象,如果该方法是静态方法,则该参数可以为null;第二个参数是一个可变参数列表,用于传入该方法的参数。
例如,以下代码使用反射机制调用了`MyClass`类中的`add`方法:
```
MyClass obj = new MyClass();
Method method = MyClass.class.getMethod("add", int.class, int.class);
int result = (int) method.invoke(obj, 1, 2);
```
这里,我们首先实例化了`MyClass`类的对象`obj`,然后通过`MyClass.class.getMethod()`方法获取了`add`方法的`Method`实例。最后,我们调用了`method.invoke()`方法,传入`obj`对象和两个int类型的参数1和2,得到了返回值并将其转换为int类型的`result`变量中。