利用反射机制编写一个程序,这个程序能指定调用类的某个方法及构造方法,并把操作信息输出到控制台。
时间: 2024-05-14 13:16:20 浏览: 101
好的,以下是一个示例代码:
```java
import java.lang.reflect.*;
public class ReflectionDemo {
public static void main(String[] args) {
try {
// 获取类对象
Class<?> c = Class.forName("java.util.ArrayList");
// 获取构造方法并调用
Constructor<?> constructor = c.getConstructor();
Object object = constructor.newInstance();
// 获取方法并调用
Method method = c.getMethod("add", Object.class);
method.invoke(object, "Hello World");
// 输出操作信息
System.out.println("调用类名:" + c.getName());
System.out.println("调用构造方法:" + constructor.toGenericString());
System.out.println("调用方法名:" + method.getName());
System.out.println("调用方法参数类型:" + method.getParameterTypes()[0].getName());
System.out.println("调用方法返回值类型:" + method.getReturnType().getName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个程序使用了反射机制,通过获取类对象、构造方法和方法,并调用它们。然后输出了调用的类名、构造方法、方法名称、方法参数类型和返回值类型等信息。当然,这只是一个简单的示例,实际应用可能需要更加复杂的处理。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)