Reputation: 39
In Java, I am trying to create an instance of a class that gets passed as a parameter. For instance:
public Class<? extends superclass> theClass;
public constructor(Class<? extends superclass> myClass){
this.theClass = myClass;
}
public superclass getInstance(){
return < AN INSTANCE OF theClass >
}
I do not know how I would create an instance of theClass
...
Is this possible, or will I need to find another way of doing it?
Any help is much appreciated.
Upvotes: 1
Views: 108
Reputation: 1074138
Yes, it's possible:
return this.theClass.newInstance();
More in java.lang.Class
and java.lang.reflect
, including a way to find other constructors that the class may have and a means of calling them with arguments.
For instance, suppose you know you need to call a constructor that accepts a String
argument. You can use getConstructor
to locate that constructor:
Constructor ctor = this.theClass.getConstructor(String.class);
...and then call it
return ctor.newInstance("the string");
Upvotes: 2
Reputation: 72844
You can call Class#newInstance()
:
public Superclass getInstance() throws InstantiationException, IllegalAccessException {
return theClass.newInstance();
}
From the Javadocs:
Creates a new instance of the class represented by this
Class
object. The class is instantiated as if by anew
expression with an empty argument list. The class is initialized if it has not already been initialized.
Upvotes: 2