我想使用class . newinstance(),但我实例化的类没有null构造函数。因此,我需要能够传入构造函数参数。有办法做到这一点吗?
当前回答
假设您有以下构造函数
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
你需要像这样表明你打算使用这个构造函数:
Class classToLoad = MyClass.class;
Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int
Long l = new Long(88);
String s = "text";
int i = 5;
classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
其他回答
可以使用getConstructor(…)获取其他构造函数。
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
编辑:根据评论似乎指向类和方法名是不够的一些用户。要了解更多信息,请参阅获取构造函数并调用它的文档。
我觉得这正是你想要的 http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
虽然它看起来是一条死线,但有人可能会发现它有用
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
不要使用Class.newInstance();为什么Class.newInstance()是邪恶的?
像其他答案说,使用Constructor.newInstance()代替。
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?