JAVA反射,如何获取带有不定参数的方法
时间: 2023-05-11 14:02:51 浏览: 74
您可以使用Java反射中的getMethod()方法来获取带有不定参数的方法。该方法需要传递两个参数:方法名称和参数类型的Class数组。在参数类型的Class数组中,您可以使用通配符Class<?>来表示不定参数。例如,以下代码可以获取名为"myMethod"的带有不定参数的方法:
```
Class<?>[] parameterTypes = new Class<?>[] { String.class, int.class, String[].class };
Method method = MyClass.class.getMethod("myMethod", parameterTypes);
```
其中,MyClass是包含myMethod方法的类的名称。在上面的代码中,第三个参数类型为String[].class,表示该方法可以接受任意数量的String类型参数。
相关问题
java 反射 构造函数 参数_反射获取带参数的构造方法
反射获取带参数的构造方法可以通过以下步骤实现:
1. 获取指定类的 Class 对象。
```java
Class<?> clazz = MyClass.class;
```
2. 获取指定参数列表的构造方法。
```java
Constructor<?> constructor = clazz.getConstructor(paramType1.class, paramType2.class, ...);
```
其中,`paramType1.class`、`paramType2.class` 是构造方法的参数类型,需要根据实际情况进行替换。
3. 通过构造方法创建对象。
```java
Object obj = constructor.newInstance(param1, param2, ...);
```
其中,`param1`、`param2` 是构造方法的实际参数,需要根据实际情况进行替换。
完整代码示例:
```java
class MyClass {
private int num;
private String str;
public MyClass(int num, String str) {
this.num = num;
this.str = str;
}
public void print() {
System.out.println("num: " + num + ", str: " + str);
}
}
public class Main {
public static void main(String[] args) throws Exception {
// 获取带参数的构造方法
Constructor<?> constructor = MyClass.class.getConstructor(int.class, String.class);
// 创建对象
Object obj = constructor.newInstance(1, "hello");
// 调用方法
MyClass myClass = (MyClass) obj;
myClass.print();
}
}
```
输出结果:
```
num: 1, str: hello
```
JAVA 如何反射获取方法的参数
可以使用Java的反射机制中的Method类中的getParameterTypes()方法来获取方法的参数类型,例如:
```java
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class ReflectionExample {
public void exampleMethod(String name, int age) {
// method body here
}
public static void main(String[] args) {
Class<?> clazz = ReflectionExample.class;
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method name: " + method.getName());
Parameter[] parameters = method.getParameters();
for (Parameter parameter : parameters) {
System.out.println("Parameter name: " + parameter.getName());
System.out.println("Parameter type: " + parameter.getType());
}
}
}
}
```
这段代码使用反射获取了ReflectionExample类中所有方法的参数类型,并打印出来。其中,getMethod()方法可以获取指定名称和参数类型的方法,getDeclaredMethod()方法可以获取所有声明的方法。而getParameterTypes()方法可以获取方法的参数类型。