How to Use Class.Newinstance() with Constructor Arguments

How to create instance of a class with the parameters in the constructor using reflection?

You need to say which constructor you want to use a pass it arguments.

Car c = Car.class.getConstructor(String.class).newInstance("Lightning McQueen");

Creating new instance from Class with constructor parameter

You can use the Class.getConstructor(paramsTypes...) method and call newInstance(..) on the constructor. In your case:

Compressor.class.getConstructor(Class.class).newInstance(Some.class);

Calling Class.newInstance with null arguments causing IllegalArgumentException

It looks like the problem is that you're passing a List instead of an array:

object_to_add = (ObjectImplementation) constructor.newInstance(argArrayOut);
// Passing a List ^^^^^^^^^^^

You need to do this instead:

object_to_add = (ObjectImplementation) constructor.newInstance(argArrayOut.toArray());

You don't say in your post that argArrayOut is a List, but it obviously is one because you call the add method on it.

Constructor.newInstance with Object[] argument

try this (not tested) :

constructor.newInstance(new Object[]{array});

because newInstance expects an array of Object (the different args), and your case is ambiguous, as your param is an array of Object.

Instantiate a class object with constructor that accepts a string parameter?

Class.newInstance invokes the no-arg constructor (the one that doesn't take any parameters). In order to invoke a different constructor, you need to use the reflection package (java.lang.reflect).

Get a Constructor instance like this:

Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);

The call to getConstructor specifies that you want the constructor that takes a single String parameter. Now to create an instance:

Object o = cons.newInstance("JLabel");

And you're done.

P.S. Only use reflection as a last resort!

Reflection - Getting New Instance of unknown classes with unknown number of constructor parameters

In general, you can't "create new instances of any class with any number of parameters". If there is not such constructor then you will not be able to call it.

Next, Class.getConstructor find the constructor with given formal parameter types, not assignment-compatible types. So if you have Foo(Number) you'll not find this constructor with Foo.class.getConstructor(Long.class). You'll have to iterate over Class.getConstructors and search for the constructor which has parameter types assignment-compatible types of your parameters.

Luckily, this was done a thousand times already. See ConstructorUtils.invokeConstructor from Commons BeanUtils, for instance. The implementation is far from trivial.

Java 9 replace Class.newInstance

These two calls invoke the same constructor, the zero-argument constructor:

  1. klass.newInstance()
  2. klass.getDeclaredConstructor().newInstance()

Both perform the same run-time check to verify the caller's access, if the constructor is not public. The only difference is that #2 wraps any checked exceptions instead of directly throwing. Otherwise they are identical and you can replace one with the other.

But this is different:


  1. klass.getConstructor().newInstance()

because it can only return a public constructor. It throws a NoSuchMethodException if the constructor is not public.

So you can't change it to getConstructor() unless you know the constructor is public.

How do I use getConstructor(params).newInstance(args)?

In Java this is called Reflection.

Assuming the class has this constructor, otherwise you will get a NoSuchMethod exception I believe.

clazz.asSubclass(asSubclassOfClass)
.getConstructor(String.class,XYZ.class)
.newInstance("howdy",XyzObj);

Since you are new to Java, let me give you an easier so that you can understand what's going on under the hood when you do this.

Assume you have the following class:

public class ParentClazz{
String someVar;
public ParentClazz(){
someVar="test";
}
public ParentClazz(String someVar){
System.out.println("I have been invoked");
this.someVar=someVar;
}
}

Then you have the following main method:

public static void main(String[] args) throws ParseException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
ParentClazz.class.asSubclass(ParentClazz.class).getConstructor(String.class).newInstance("howdy");
}

If you run this you will notice the console output print message - I have been invoked. This means that using reflection you have invoked the constructor of ParentClazz.

You can do the same thing if the scenario allows you is by using standard object creation process:

ParentClazz clazz = new ParentClazz("howdy");

Hope this helps you understand it.



Related Topics



Leave a reply



Submit