如何检查java类中是否有特定的方法?
我有一个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的名称和参数)。
假设您有一个不带args的方法:
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[]) null); }
假设您有一个采用native 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(, invoke(this, Integer.valueOf(10))); }
假设你有一个方法需要盒装Integer
args:
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(, invoke(this, Integer.valueOf(10))); }
使用上面的soln来调用方法不会给你编译错误。 根据@Foumpie更新
使用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; } }
编辑:
因此,如果存在,则需要调用该方法。 这是你如何做到的:
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. } }
随着spring:
Method method = ReflectionUtils.findMethod(TheClass, "methodName"); if (method != null) { //do what you want }
如果使用Spring Framework,最简单的方法是使用ReflectionUtils.findMethod()实用程序。
您可以在Java中使用Reflection http://docs.oracle.com/javase/tutorial/reflect/index.html
或http://docs.oracle.com/javase/tutorial/reflect/member/methodType.html