java 通过反射创建对象 工具类
时间: 2023-07-05 18:32:44 浏览: 64
可以使用以下代码创建对象的工具类:
```java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectionUtil {
/**
* 通过类名创建对象
* @param className 类名
* @return 创建的对象
*/
public static Object createObject(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class<?> clazz = Class.forName(className);
return clazz.newInstance();
}
/**
* 通过类名和构造函数参数创建对象
* @param className 类名
* @param args 构造函数参数
* @return 创建的对象
*/
public static Object createObject(String className, Object... args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> clazz = Class.forName(className);
Class<?>[] parameterTypes = new Class[args.length];
for (int i = 0; i < args.length; i++) {
parameterTypes[i] = args[i].getClass();
}
Constructor<?> constructor = clazz.getConstructor(parameterTypes);
return constructor.newInstance(args);
}
}
```
其中,`createObject(String className)` 方法通过类名创建对象,`createObject(String className, Object... args)` 方法通过类名和构造函数参数创建对象。使用时,只需要传入类名和参数即可。注意,如果类的构造函数是私有的,需要使用 `getDeclaredConstructor()` 方法获取构造函数,并设置 `setAccessible(true)` 来允许访问私有构造函数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)