开发者

Is it possible to call the default-constructor instead of the zero-argument constructor?

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜