Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: newInstance of class that has no default constructor

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.

like image 334
GermanK Avatar asked Sep 08 '10 20:09

GermanK


People also ask

What happens when there is no default constructor in Java?

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.

What if there is no default constructor available?

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.

Can a class not have a default constructor?

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.

Does every class in Java automatically have a default constructor?

The compiler automatically provides a no-argument, default constructor for any class without constructors.


1 Answers

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);                } } 
like image 150
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet