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,