Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Create new Instance using Reflection without knowing constructor params

I need to create new instances of many classes. I'm using reflection but when I make c.newInstance(), the classes without 'empty parameter constructor' throws an java.lang.InstantiationException.

Now, how can i do to create instances of every classes ?

I know that i can use c.getConstructor(Class).newinstance(params) to create instances of classes that doesn't have 'empty parameter constructor', but i do not know the params of each classes.

One more thing, all those classes extend from another class called ParentClass, so one workaround that i could use is to include some code in the ParentClass that force the child classes to implement an 'empty parameter constructor', but don't know how to do this.

Thanks in advance !

like image 707
oriuken Avatar asked Dec 07 '12 19:12

oriuken


People also ask

Can you make instances of a class without a constructor?

Java doesn't require a constructor when we create a class. However, it's important to know what happens under the hood when no constructors are explicitly defined. The compiler automatically provides a public no-argument constructor for any class without constructors. This is called the default constructor.

How do you create an instance of a reflection in Java?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.

Can we create a class without constructor in Java?

Note: It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.

Can you create an instance of a class using its constructor?

When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.


1 Answers

You can call Class.getConstructors() to get all the constructors for a given class.

On each Constructor, you can call Constructor.getGenericParameterTypes() to learn which parameters it expects.

  • JavaDoc for Class
  • JavaDoc for Constructor
like image 105
jahroy Avatar answered Oct 27 '22 19:10

jahroy