I have a method that needs to create an array of objects of a certain type. Here’s a part of it:
public void myMethod() {
for (int i = 0; i < something.length; i++) {
ViewerSorter sorter = new IdeaTableSorter(i);
.....
.....
}
}
I want this method to work with all kinds of ViewerSorter objects, not just be coupled with IdeaTableSorter, but since I have to create a bunch of these objects I want to pass a reference to myMethod telling it which class to instantiate.
Is there a way to do this without using the Reflection API?
You can pass a
Factoryobject that instantiates your class. This would be the Abstract factory pattern. For example:And then:
where:
Class.newInstance()is not exactly the reflection API, though I assume you meant this option as undesirable. But give it a try – this approach is the same – you pass a factory (in this caseClass) and call a creation method (.newInstance())