Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Instance unknown subclass with parameterized constructor in runtime

807589Apr 19 2008 — edited Aug 7 2008
Hi,

I have an abstract superclass, with a constructor which takes a parameter
public abstract class SuperClass {
	public SuperClass(String arg) {
		// some stuff
	};
}
And some subclasses with the same constructor signature
public class SubClass1 extends SuperClass {
	public SubClass1(String arg) {
		super(arg);
		// some stuff
	}
}
I would like to know how can i create a instance of the subclass if i just have its name in a String (it will be implemented by third party).
I already tried this piece of code, but it prevents me of passing the parameter to the constructor.
	public static void main(String[] args) {
		String className = "SubClass1";
		Class clazz = null;
		try {
			clazz = Class.forName(className);
		} catch (ClassNotFoundException e) {
		}
		try {
			SuperClass c = (SuperClass)clazz.newInstance();
		} catch (InstantiationException e) {
		} catch (IllegalAccessException e) {
		}
	}
Regards,

Fabiano.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 4 2008
Added on Apr 19 2008
11 comments
747 views