How would one go about checking to see if a method exists for a class in Java? Would a try {...} catch {...}
statement be good practice?

- 8,496
- 3
- 36
- 68
-
Are you using reflection? Otherwise, I'm not sure what you're asking... – Neil Aug 14 '11 at 17:59
-
What does try/catch have to do with method existence? Unless you are referring to a situation like with the `Iterator` interface where implementation of `remove` are permitted to throw a `UnsupportedOperationException`? – Ken Wayne VanderLinde Aug 14 '11 at 18:00
-
1What kind of checking for existing methods are you talking about? Reflection? – Jaka Aug 14 '11 at 18:00
-
1I'm trying to see if a desired method that may not be present exists so that I know if I can call it. I thought I would be able to put the call inside a try catch, and catch an error if the method does not exist. In case it isn't obvious I'm not exactly a Java pro! – jrtc27 Aug 14 '11 at 21:17
7 Answers
I assume that you want to check the method doSomething(String, Object)
.
You might try this:
boolean methodExists = false;
try {
obj.doSomething("", null);
methodExists = true;
} catch (NoSuchMethodError e) {
// ignore
}
This will not work, since the method will be resolved at compile-time.
You really need to use reflection for it. And if you have access to the source code of the method you want to call, it's even better to create an interface with the method you want to call.
[Update] The additional information is: There is an interface that may exist in two versions, an old one (without the wanted method) and a new one (with the wanted method). Based on that, I suggest the following:
package so7058621;
import java.lang.reflect.Method;
public class NetherHelper {
private static final Method getAllowedNether;
static {
Method m = null;
try {
m = World.class.getMethod("getAllowedNether");
} catch (Exception e) {
// doesn't matter
}
getAllowedNether = m;
}
/* Call this method instead from your code. */
public static boolean getAllowedNether(World world) {
if (getAllowedNether != null) {
try {
return ((Boolean) getAllowedNether.invoke(world)).booleanValue();
} catch (Exception e) {
// doesn't matter
}
}
return false;
}
interface World {
//boolean getAllowedNether();
}
public static void main(String[] args) {
System.out.println(getAllowedNether(new World() {
public boolean getAllowedNether() {
return true;
}
}));
}
}
This code tests whether the method getAllowedNether
exists in the interface, so it doesn't matter whether the actual objects have the method or not.
If the method getAllowedNether
must be called very often and you run into performance problems because of that, I will have to think of a more advanced answer. This one should be fine for now.

- 40,703
- 10
- 88
- 121
-
The method is not in my code but in a linked jar - will this work for that? – jrtc27 Aug 14 '11 at 18:03
-
Can you say which method it is? Does the method come from an `interface`, so you can simply query its existence with the `instanceof` operator? – Roland Illig Aug 14 '11 at 18:06
-
the compiler will go through the jars that you specify and find all the methods, if it will not find something, it will complain with an error message – Jaka Aug 14 '11 at 18:11
-
I will be compiling against a version that has the method. It is a plugin for Bukkit (google it) and so there are versions with and without the method - if it does not exist I do not need it. Not sure about the interface thing - will check later. How would that work if it were? – jrtc27 Aug 14 '11 at 21:21
-
Yes it is an interface - if it helps I'm trying to see if the getAllowNether() method exists for https://github.com/Bukkit/Bukkit/blob/master/src/main/java/org/bukkit/World.java (old versions lack it). – jrtc27 Aug 14 '11 at 21:28
-
It's only called once when a player tries to use a Nether portal (you DO play Minecraft, don't you :P) so not that often. I will test this. Thanks, jrtc27 – jrtc27 Aug 15 '11 at 07:52
-
Calling the method via reflection might become a bottleneck if it is used too often. In that case I would create an interface and two implementations: one that calls the `getAllowNether` method from the interface and one that doesn't. At runtime I would choose the proper implementation via `Class.forName`. The point is that the code needs to be compiled agains the new version of the interface, and (if the interface doesn't have that method at runtime) the class calling the `getAllowNether` must not be referenced at all. – Roland Illig Aug 15 '11 at 11:26
-
Sorry for taking so RIDICULOUSLY long to test this! anyway I ca confirm that this works, so thank you. It isn't a bottleneck (really) in my situation (I'm sure other things I'm doing are terribly inefficient!). – jrtc27 Aug 19 '11 at 22:29
Reflection API throws NoSuchMethodException
when using Class.getMethod(...)
functions.
Otherwise Oracle has a nice tutorial about reflection http://download.oracle.com/javase/tutorial/reflect/index.html

- 1,205
- 12
- 19
In java this is called reflection. The API allows you to discover methods and call them at runtime. Here is a pointer to the docs. It's pretty verbose syntax but it'll get the job done:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/

- 74
- 2
I would use a separate method to handle the exception and have a null check to check if method exists
Ex : if (null != getDeclaredMethod(obj, "getId", null))
do your stuff...
private Method getDeclaredMethod(Object obj, String name, Class<?>... parameterTypes) {
// TODO Auto-generated method stub
try {
return obj.getClass().getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

- 11,377
- 5
- 59
- 58

- 2,683
- 3
- 17
- 14
If you're using Spring in your project you may check ReflectionUtil.findMethod(..)
. It returns null if method does not exist or does not match your requirements. Documentation.

- 2,057
- 21
- 16
Roland Illig is correct, but wanted to add in an example of how to check if a method exists that requires a parameter using Class.getMethod. Can also use Class.getDeclaredMethod if you are trying to access a private method.
class World {
public void star(String str) {}
private void mars(String str) {}
}
try {
World.class.getMethod("star", String.class);
World.class.getDeclaredMethod("mars", String.class);
} catch (Exception e) {}

- 8,474
- 9
- 40
- 53
Other solution:
public static <O> boolean existsMethod(final String methodName, final O o) {
return Stream.of(o.getClass().getMethods()).map(Method::getName).anyMatch(methodName::equals);
}

- 1
- 1