简体   繁体   English

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

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

I have an xml schema (generated automatically using trang) which keeps changing.我有一个不断变化的 xml 模式(使用 trang 自动生成)。 These changes are not very elaborate.这些变化不是很详细。 Only some elements are added or deleted from this schema.仅在此架构中添加或删除了一些元素。 From this schema, I am generating java classes (using cxf) by which I will unmarshall the xml document.从这个模式,我生成 java 类(使用 cxf),我将通过它解组 xml 文档。

As schema changes, my auto-generated java classes also change.随着模式的变化,我自动生成的 java 类也会发生变化。 Again, as with schema, changes in java classes are not very big.同样,与模式一样,java 类的变化不是很大。 For instance, if an element say elemA is added to schema;例如,如果一个元素说elemA被添加到架构中; some related functions say getElemA() and setElemA() are added to auto-generated java class.一些相关的函数说getElemA()setElemA()被添加到自动生成的 java 类中。

Now how would I make sure that a particular function exists in these auto-generated classes?现在我如何确保这些自动生成的类中存在特定的函数? One solution is to hand-write the schema such that all possible elements of xml are covered.一种解决方案是手写模式,以便涵盖 xml 的所有可能元素。 This is what I'll ultimately do.这就是我最终要做的。 But for now, I have not fixed the format of xml file.但目前,我还没有固定 xml 文件的格式。

UPDATE :更新 :

There is a possibility that a method getElemA() may be defined in auto-generated classes.有可能在自动生成的类中定义getElemA()方法。 I do not have control over the auto-generation of these classes.我无法控制这些类的自动生成。 But in my main class, if have following code,但是在我的主课中,如果有以下代码,

If method getElemA exists then 
     ElemA elemA = getElemA()

This code will always be there in my main class.这段代码将始终存在于我的主类中。 If method getElemA() is generated in one of the auto-generated class then there is no problem.如果方法getElemA()在自动生成的类之一中生成,则没有问题。 But if this method is not generated then compilers complain that this method does not exists in any of the class.但是如果没有生成这个方法,那么编译器就会抱怨这个方法在任何类中都不存在。

Is there any way that I can make compiler not to complain about this function at compile time?有什么办法可以让编译器在编译时不抱怨这个函数吗?

One method is mentioned by @missingfaktor and another is below (if you know the name and parameters of the api). @missingfaktor 提到了一种方法,另一种在下面(如果您知道 api 的名称和参数)。

Say you have one method which takes no args:假设您有一种不需要参数的方法:

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

Invoke it if present:如果存在则调用它:

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

Say you have one method which takes native int args:假设您有一种采用本机int args 的方法:

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

Invoke it if present:如果存在则调用它:

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

Say you have one method which takes boxed Integer args:假设您有一种采用盒装Integer参数的方法:

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

Invoke it if present:如果存在则调用它:

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

Using the above soln to invoke method won't give you compilation errors.使用上面的 soln 来调用方法不会给你编译错误。 Updated as per @Foumpie根据@Foumpie 更新

Usereflection .使用反射

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

Edit:编辑:

So you want to invoke the method if it exists.所以你想调用该方法(如果它存在)。 This is how you do it:这是你如何做到的:

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

With Spring:与春天:

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

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

Another way is by using Java 8 stream:另一种方法是使用 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