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 Factory
object that instantiates your class. This would be the Abstract factory pattern . For example:
interface ViewSorterFactory {
ViewSorter create();
}
class IdeaTableSorterFactory implements ViewSorterFactory {
ViewSorter create() { return new IdeaTableSorter(); }
}
class FooTableSorterFactory implements ViewSorterFactory {
ViewSorter create() { return new FooSorter(); }
}
And then:
myMethod(new IdeaTableSorterFactory());
where:
for (int i = 0; i < something.length; i++) {
ViewerSorter sorter = factory.create();
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 case Class
) and call a creation method ( .newInstance()
)
Yes, you can do this using reflection. However, it would arguably be cleaner to use the Factory pattern:
public interface IViewerSorterFactory {
ViewerSorter create(int i);
}
public void myMethod(IViewerSorterFactory factory) {
for (int i = 0; i < something.length; i++) {
ViewerSorter sorter = factory.create(i);
.....
.....
}
}
You could pass in an object with a method that creates viewer sorters—a provider of sorts.
public void myMethod(ViewerSorterProvider creator) {
for (int i = 0; i < something.length; i++) {
ViewerSorter sorter = creator.create(i);
.....
.....
}
}
public interface ViewerSorterProvider {
ViewerSorter create(int i);
}
You could pass a factory object into the method that can create the appropriate types.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.