Reputation: 1391
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.
Upvotes: 22
Views: 41934
Reputation: 11656
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();
}
Upvotes: 7
Reputation: 32680
You're looking for Reflection.
Your method would look something like this:
public void m1(Class c) {
try {
Object obj = c.newInstance();
//do something with your new instance
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
}
}
The Oracle doc for the Reflection API is here
Upvotes: 3
Reputation: 136072
Yes you can
void x(Class cls) throws InstantiationException, IllegalAccessException {
cls.newInstance();
}
Note that Class.newInstance may fail with
IllegalAccessException - if the class or its nullary constructor is not accessible.
InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.
see API for more
Upvotes: 1
Reputation: 41975
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.
Upvotes: 19
Reputation: 93060
You need to use reflection to do that, but yeah it is certainly possible.
void MyMethod(Class className)
{
try {
Object obj = className.newInstance();
//obj is a newly created object of the passed in type
}
catch (Exception ex) { }
}
Upvotes: 4