I am trying to efficiently search weather a subclass implements a method that I have the name of in a string called _szMethodName. I can get an array of all the methods that the subclass implements by doing Method[] _arrClassMethodsList = class.getMethods();. I can then compare the name of the method to the stringName of the function that I am looking for to determine weather or not the class implements that particular method. Currently I have this working in a for loop but this gets slow as the subclass grows.
For Loop implementation:
for (Method method : class.getMethods()){
if(method.getName().equals(_szMethodName)){
//method exists in subclass
break;
}
}
The array of methods from (Only in Java >=7). I was hoping that I could leverage this by using a binary-search or some other optimization on the array instead of using the for loop. However, I have not yet been able to figure out how to implement Java's binary search function on the array. I have tried using comparator or and comparable but have not yet had success. My most recent implementation of comparator is below but has errors that I have not yet been able to resolve. class.getMethods() is sorted alphabetically.
Current attempt using comparator:
Comparator<Method> c = new Comparator <Method>() {
public int compare(Method method, String string) {
return method.getName().compareTo(string);
}
};
Method[] _arrClassMethodsList = class.getMethods();
int index = Arrays.binarySearch(_arrClassMethodsList, _szMethodName, c);
Any help or examples on how to get this working would be greatly appreciated. Thanks!
getMethods()says the order is implementation dependent (The javadoc explicitly says "The elements in the array returned are not sorted and are not in any particular order"). I believe that in Java 7 it is alphabetical, but I believe in Java 6 it used to be definition order. So don't depend on it.