Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing class type as parameter and creating instance of it

Tags:

I want to pass a class type as a parameter to a method in java.all of which have the same constructor parameter.and create an instance of that Class in that method.is this possible?

Update after some years: do checkout Sapnesh Naik's answer to this, it seems to be the most up-to-date. I have not accepted is as an answer as I do not have a running java stack.
P.S: Give me a shout if you can verify.

like image 221
user2268997 Avatar asked Apr 11 '13 06:04

user2268997


People also ask

Can we pass class as a parameter?

Yes, you can pass the object of a class inside a method as an argument.

How do you create an instance of a class?

Instantiating a ClassThe 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. The new operator returns a reference to the object it created.

Which method returns class type of the argument passed as parameter?

clone() method or define a constructor that takes an object of its class as a parameter.

How do you pass a class object as a parameter in Java?

We have a method coypObject() which accepts an object of the current class and initializes the instance variables with the variables of this object and returns it. In the main method we are instantiating the Student class and making a copy by passing it as an argument to the coypObject() method.


2 Answers

Using reflection to create the instance:

Object obj = clazz.newInstance();

This will use the default no-arg constructor to create the instance.

Constructor<?> constructor = clazz.getConstructor(String.class);
Object object = constructor.newInstance(new Object[] { strArgument });

To create the instance if you have some other constructor which takes arguments.

like image 190
Narendra Pathai Avatar answered Oct 16 '22 05:10

Narendra Pathai


newInstance() is Deprecated.

This method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) java.lang.reflect.InvocationTargetException.

The deprecated call:

clazz.newInstance()

Can be replaced by:

clazz.getDeclaredConstructor().newInstance()

Example:

void MyMethod(Class type) throws InstantiationException, IllegalAccessException {
    type.getDeclaredConstructor().newInstance();
}
like image 35
Sapnesh Naik Avatar answered Oct 16 '22 04:10

Sapnesh Naik