Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting whether a method/function exists in Java

Is there a method/function in Java that checks if another method/function is available just like function_exists(functionName) in PHP?

Here I am referring to a method/function of static class.

like image 374
Mo3z Avatar asked Oct 12 '11 14:10

Mo3z


1 Answers

You can find out if a method exists in Java using reflection.

Get the Class object of the class you're interested in and call getMethod() with the method name and parameter types on it.

If the method doesn't exist, it will throw a NoSuchMethodException.

Also, please note that "functions" are called methods in Java.

Last but not least: keep in mind that if you think you need this, then chances are that you've got a design problem at hand. Reflection (which is what the methods to inspect the actual Java classes is called) is a rather specialized feature of Java and should not generally be used in business code (although it's used quite heavily and to some nice effects in some common libraries).

like image 68
Joachim Sauer Avatar answered Sep 21 '22 21:09

Joachim Sauer