Detecting if a method / function exists in Java

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

Here I mean the method / function of a static class.

+6
source share
7 answers

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

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

If the method does not exist, it will throw a NoSuchMethodException .

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

And last but not least, keep in mind that if you think you need it, then there is a chance that you have design problems. Reflection (this is what the methods of checking actual Java classes are called) is a rather specialized Java function and should usually not be used in business code (although it was used quite widely with some good effects in some common libraries).

+20
source

I suspect you are looking for Class.getDeclaredMethods and Class.getMethods , which will give you class methods. Then you can check if the one you are looking for exists or not, and what are its parameters, etc.

+9
source

You can use Reflections to search if there is a method:

 public class Test { public static void main(String[] args) throws NoSuchMethodException { Class clazz = Test.class; for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals("fooBar")) { System.out.println("Method fooBar exists."); } } if (clazz.getDeclaredMethod("fooBar", null) != null) { System.out.println("Method fooBar exists."); } } private static void fooBar() { } } 

But Reflection is not very fast, so be careful when to use it (maybe cache it).

+7
source

Try using the Class.getMethod() method of class class =)

 public class Foo { public static String foo(Integer x) { // ... } public static void main(String args[]) throws Exception { Method fooMethod = Foo.class.getMethod("foo", Integer.class); System.out.println(fooMethod); } } 
+4
source

Here is my solution using reflection ...

  public static boolean methodExists(Class clazz, String methodName) { boolean result = false; for (Method method : clazz.getDeclaredMethods()) { if (method.getName().equals(methodName)) { result = true; break; } } return result; } 
+2
source

You can use the reflection API to achieve this.

 YourStaticClass.getClass().getMethods(); 
+1
source

You can do it as follows

 Obj.getClass().getDeclaredMethod(MethodName, parameterTypes) 
+1
source

Source: https://habr.com/ru/post/899134/


All Articles