繁体   English   中英

如何检查java类中是否有特定的方法?

[英]How to check if a java class has a particular method in it?

我有一个不断变化的 xml 模式(使用 trang 自动生成)。 这些变化不是很详细。 仅在此架构中添加或删除了一些元素。 从这个模式,我生成 java 类(使用 cxf),我将通过它解组 xml 文档。

随着模式的变化,我自动生成的 java 类也会发生变化。 同样,与模式一样,java 类的变化不是很大。 例如,如果一个元素说elemA被添加到架构中; 一些相关的函数说getElemA()setElemA()被添加到自动生成的 java 类中。

现在我如何确保这些自动生成的类中存在特定的函数? 一种解决方案是手写模式,以便涵盖 xml 的所有可能元素。 这就是我最终要做的。 但目前,我还没有固定 xml 文件的格式。

更新 :

有可能在自动生成的类中定义getElemA()方法。 我无法控制这些类的自动生成。 但是在我的主课中,如果有以下代码,

If method getElemA exists then 
     ElemA elemA = getElemA()

这段代码将始终存在于我的主类中。 如果方法getElemA()在自动生成的类之一中生成,则没有问题。 但是如果没有生成这个方法,那么编译器就会抱怨这个方法在任何类中都不存在。

有什么办法可以让编译器在编译时不抱怨这个函数吗?

@missingfaktor 提到了一种方法,另一种在下面(如果您知道 api 的名称和参数)。

假设您有一种不需要参数的方法:

Method methodToFind = null;
try {
  methodToFind = YouClassName.class.getMethod("myMethodToFind", (Class<?>[]) null);
} catch (NoSuchMethodException | SecurityException e) {
  // Your exception handling goes here
}

如果存在则调用它:

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);
}

假设您有一种采用本机int args 的方法:

Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { int.class });

如果存在则调用它:

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)));
}

假设您有一种采用盒装Integer参数的方法:

Method methodToFind = null;
methodToFind = YouClassName.class.getMethod("myMethodToFind", new Class[] { Integer.class });

如果存在则调用它:

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)));
}

使用上面的 soln 来调用方法不会给你编译错误。 根据@Foumpie 更新

使用反射

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;
  }
}

编辑:

所以你想调用该方法(如果它存在)。 这是你如何做到的:

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.
  }
}

与春天:

Method method = ReflectionUtils.findMethod(TheClass, "methodName");
if (method != null) {
  //do what you want
}

如果您使用 Spring Framework,最简单的方法是使用ReflectionUtils.findMethod()实用程序。

另一种方法是使用 Java 8 流:

  Optional<Method> methodToFind =
                Arrays.stream(clazz.getMethods()).
                        filter(method -> "methodName".equals(method.getName())).
                        findFirst();
        if (methodToFind.isPresent()) {
            // invoke method or any logic needed
            ///methodToFind.get().
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM