rasnauf
rasnauf

Reputation: 353

Create an array of classes in Java (not objects)?

I want to create an array of classes, not objects. I want to be able to access static functions of each class that have the same name, like so:

for (int i = 0; i < array.length; ++i) {
    array[i].staticMethod();
}

Where array[i] would be syntactically interchangable with the name of a class, like Integer.

Upvotes: 1

Views: 4240

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198103

You don't really have any choice but to use Class objects in an array, Class<?>[] array = new Class<?>[10], and then invoke the static method reflectively, e.g.

array[i].getMethod("staticMethod", ArgType1.class, ArgType2.class)
    .invoke(null, arg1, arg2);

Given your stated goal, that is the very closest approximation available in Java. You cannot have lowercase-c classes stored as variables or as data in arrays.

EDIT: Given your stated goal of benchmarking the efficiency of sorting algorithms, then reflection overhead would skew those results unpleasantly. You're better off finding another way to write it, rather than what you're trying to do with an array of classes, which won't really work.

if you're in Java 8, then I'd probably write something like

List<Consumer<int[]>> sorters = Arrays.asList(
    Sort1::sort, Sort2::sort, Sort3::sort);
for (Consumer<int[]> sorter : sort) {
  int[] array = createNewRandomArray();
  sorter.accept(array);
}

If you're not, then I'd write something like

   enum SortingVariant {
     SORT1 {
       @Override void sort(int[] array) { Sort1.sort(array); }
     },
     SORT2 {
       @Override void sort(int[] array) { Sort2.sort(array); }
     };
     abstract void sort(int[] array);
   }

   for (SortingVariant sorter : SortingVariant.values()) {
     sorter.sort(getNewRandomArray());
   }

In both these cases, the key goal is to create a list of objects which implement a known method that can be used to sort, rather than trying to magically create a list of classes and invoke a method that happens to have the same name in each of them.

Upvotes: 2

DBug
DBug

Reputation: 2566

You define an array of classes like this:

Class<?>[] classArray = new Class<?>[10];

Upvotes: 2

Related Questions