How to check if a java class has a particular method in it?
Use reflection.
import java.lang.reflect.Method;
boolean hasMethod = false;
Method[] methods = foo.getClass().getMethods();
for (Method m : methods) {
if (m.getName().equals(someString)) {
hasMethod = true;
break;
}
}
Edit:
So you want to invoke the method if it exists. This is how you do it:
if (m.getName().equals(someString)) {
try {
Object result = m.invoke(instance, argumentsArray);
// Do whatever you want with the result.
} catch (Exception ex) { // For simplicity's sake, I am using Exception.
// You should be handling all the possible exceptions
// separately.
// Handle exception.
}
}
One method is mentioned by @missingfaktor and another is below (if you know the name and parameters of the api).
Say you have one method which takes no args:
Method methodToFind = null;
try {
methodToFind = YouClassName.class.getMethod("myMethodToFind", (Class<?>[]) null);
} catch (NoSuchMethodException | SecurityException e) {
// Your exception handling goes here
}
Invoke it if present:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, (Object[]) null);
}
Say you have one method which takes native int
args:
Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { int.class });
Invoke it if present:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this,
Integer.valueOf(10)));
}
Say you have one method which takes boxed Integer
args:
Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { Integer.class });
Invoke it if present:
if(methodToFind == null) {
// Method not found.
} else {
// Method found. You can invoke the method like
methodToFind.invoke(<object_on_which_to_call_the_method>, invoke(this,
Integer.valueOf(10)));
}
Using the above soln to invoke method won't give you compilation errors. Updated as per @Foumpie