0

I'm having a problem when invoking a method from another class. This is the code I'm using:

Contact[] database=players1();

System.out.println(sortalg[i]);
try {
    Method method = Sorting.class.getMethod("selectionSort", Comparable[].class);
    method.invoke(database);
}

This is the method I want to invoke:

public static void selectionSort (Comparable[] data)
{
  int min;

  for (int index = 0; index < data.length-1; index++)
  {
     min = index;
     for (int scan = index + 1; scan < data.length; scan++)
        if (data[scan].compareTo(data[min]) < 0)
           min = scan;

     swap(data, min, index);
  }
}

And this is the error I get:

java.lang.IllegalArgumentException: wrong number of arguments

What arguments do I have to add?

SilverNak
  • 3,283
  • 4
  • 28
  • 44
  • What does your `Contact` class look like? – Tobias Geiselmann Sep 22 '17 at 08:44
  • 1
    Does `Contact` implement `Comparable`? – SilverNak Sep 22 '17 at 08:44
  • The method is `public static` so there's no need to use reflection here. Just call `ClassName.selectionSort(database)`. – QBrute Sep 22 '17 at 10:06
  • @Tobias Geiselmann This is what the Contact class looks like `public class Contact implements Comparable { private String firstName, lastName, phone; public Contact (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; } ` – Geert Buis Sep 25 '17 at 09:10
  • @QBrute I'm trying to call a method from a string input, so that I can loop through many different methods in one go – Geert Buis Sep 25 '17 at 09:11

1 Answers1

2

Why are you using reflections to call a static method? Assuming Contact implements Comparable, why don't you just call

Sorting.selectionSort(database);

? If you have to use reflections, you must pass the object to invoke the method on, which is in your case null:

 method.invoke(null, database);

See this question

The Frozen One
  • 281
  • 2
  • 10
  • I'd like to use reflections since I'm looping through a large amount of different sorting algorithms. I put the names of all the algorithms in a string array, and from there I figured I'd need to use reflections to call a method from a string. Adding a null to the invoke unfortunately doesn't help... – Geert Buis Sep 25 '17 at 09:08