I wish to be able to get a List/ArrayList of N new instances from a static method inherited to subclasses so that I don't have to rewrite this same function in all subclasses.
I want to implement this so that I can build a vector containg some A and B. I've tried several methods but none of them worked for me :
public class Parent {
public static List<Parent> getNInstances(int n) {
List<Parent> out = new ArrayList<>();
for (int i = 0; i < n; i++) {
Parent newChildInstance = (Parent) MethodHandles
.lookup()
.lookupClass()
.getConstructor()
.newInstance()
out.add(newChildInstance);
}
}
}
I've got the MethodHandles thing from here since I feel like I need to get the class to be able to call .getConstructor().newInstance()
which should, in theory, solve my problem. Nonetheless, this doesn't work, it gives me a NoSuchMethodException since he's not able to find the constructor from the Class given by
MethodHandles.lookup().lookupClass()
, at least I think that's why.
Here is how I would like the method .getNInstances()
to work.
public class Parent {
public Parent(){ }
public static List<Parent> getNInstances(int n) {
List<Parent> out = new ArrayList<>();
for (int i = 0; i < n; i++) {
Parent newChildInstance = ...
out.add(newChildInstance);
}
}
}
public class A extends Parent {
public A(){ }
}
public class B extends Parent {
public B(){ }
}
public class Main {
public static void main(String[] args) {
List<Parent> total = new ArrayList<>();
total.addAll(A.getNInstances(3));
total.addAll(B.getNInstances(4));
}
}
Here total should therefore be like [a, a, a, b, b, b, b] where a is an instance of A and b an instance of B, but by now, it's just empty.