是否可以调用默认构造函数而不是零参数构造函数?
我有一个 util 类,它应该使用反射调用给定 Class 对象上的方法。
现在它使用 .newInstance() 创建一个新实例,然后调用我想测试的方法。
问题是,我的一些类的零参数构造函数由于缺少依赖项等而抛出异常,并阻止我调用我真正想要测试的方法。
是否可以调用Java的默认构造函数来创建实例,而不是自定义的零参数构造函数?
I have a util class that is supposed to call a method on a given Class object using reflection.
Right now it creates a new instances using .newInstance() and then calls the method I want to test.
The problem is that the zero-arguement constructor of some of my classes throws an Exception due to missing dependencies and such and keeps me from calling the method I actually want to test.
Is it possible to call the default-constructor of Java to create the instance instead of the custom zero-argument constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果类没有定义构造函数,则只有默认构造函数。
无参数构造函数应该只接受您给它的依赖项(即没有),并且您似乎相信您仍然可以使用该类而无需额外的依赖项。
在 Sun/Oracle JVM 中,您可以使用 Unsafe.allocateInstance(Class) 来创建实例而不调用构造函数,但我会首先尝试修复您的类设计。
You only have a default constructor, if the class has no constructors defined.
The no-arg constructor should only take the dependencies you give it (i.e. none) and it appears you believe you can still use the class without additional dependencies.
In Sun/Oracle JVM you can use
Unsafe.allocateInstance(Class)
which creates an instance without calling a constructor, but I would try to fix your class design first.仅当您自己不提供构造函数时,才会创建默认构造函数。
因此,只要您的类至少有一个构造函数,就不会创建该默认构造函数。
A default constructor is only created, when you don't provide a constructor yourself.
So, as soon as your class has at least one constructor, that default constructor isn't being created.