Reputation: 1229
I have an abstract class 'A' and class 'B' and 'C' extends A. I want to create instances of these during run time based on some variable. Something like below:
public abstract class A {
public abstract int count();
}
public class B extends A {
public int count () {
//print 10;
}
}
public class C extends A {
public int count () {
//print 20;
}
}
I would use the below code to call the method count:
String token;
int i = 10;
if (i == 10) //edit
token = "B";
else
token = "C";
A a;
try {
a = (A) (Class.forName("org.source."+token)).newInstance();
} catch (Exception e) {
//print e
}
a.count();
Since I am new to java reflections, here are my 2 questions:
Is what I am doing above right (edit: in case of default constructors) ? (I am presuming yes)
The above works if the default constructor (without parameters) is called. How would I handle a situation where I have constructors that take in arguments. I am not very sure how I could use Constructor.newInstance() can be used in the above situation.
Any help appreciated,
Upvotes: 0
Views: 1163
Reputation: 1053
What you are doing is right only if you want to call the no-arg constructor, which really, is the only thing you can do with the "newInstance" method in Class. See:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#newInstance()
to invoke constructors with n-args, use the Constructor class:
See the Reflection tutorial for examples on the usages of the above:
http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
For more info.
Upvotes: 1
Reputation: 424983
Yes it will work.
If you want to use a constructor other than the default (no-args) one, read on.
Let's say for example you want to call the constructor with an int
and String
arguments. Here's the code that will do that:
Class<?> clazz = Class.forName("org.source."+ token );
Constructor<?> constructor = clazz.getConstructor(int.class, String.class);
Object object = constructor.newInstance(1, "hello");
Upvotes: 1