I'm trying to build an automatic testing framework (based on jUnit, but that's no important) for my students' homework. They will have to create constructors for some classes and also add some methods to them. Later, with the testing functions I provide, they will check if they went alright.
What I want to do is, by reflection, create a new instance of some class I want to test. The problem is that, sometimes, there is no default constructor. I don't care about that, I want to create an instance and initialize the instance variables myself. Is there any way of doing this? I'm sorry if this has been asked before, but just I couldn't find any answer.
Thanks in advance.
The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor. If we do explicitly declare a constructor of any form, then this automatic insertion by the compiler won't occur.
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define *any* constructor, then you must define *all* constructors.
If constructors are explicitly defined for a class, but they are all non-default, the compiler will not implicitly define a default constructor, leading to a situation where the class does not have a default constructor. This is the reason for a typical error, demonstrated by the following example.
The compiler automatically provides a no-argument, default constructor for any class without constructors.
Call Class.getConstructor()
and then Constructor.newInstance()
passing in the appropriate arguments. Sample code:
import java.lang.reflect.*; public class Test { public Test(int x) { System.out.println("Constuctor called! x = " + x); } // Don't just declare "throws Exception" in real code! public static void main(String[] args) throws Exception { Class<Test> clazz = Test.class; Constructor<Test> ctor = clazz.getConstructor(int.class); Test instance = ctor.newInstance(5); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With