33

I have an xml schema (generated automatically using trang) which keeps changing. 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.

As schema changes, my auto-generated java classes also change. Again, as with schema, changes in java classes are not very big. For instance, if an element say elemA is added to schema; some related functions say getElemA() and setElemA() are added to auto-generated java class.

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. This is what I'll ultimately do. But for now, I have not fixed the format of xml file.

UPDATE :

There is a possibility that a method getElemA() may be defined in auto-generated classes. 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. 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?

6 Answers 6

50

One method is mentioned by @missingfaktor and another is below (if you know the name and parameters of the 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:

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:

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. Updated as per @Foumpie

6
  • Thanks. I want to use the method and I have to write all possible methods in that class but autogenerated class may not have that method. How to make compiler ignore this at compile time?
    – Dilawar
    Jun 4, 2012 at 5:39
  • Using invoke wont give you compilation errors...check the updated ans.
    – havexz
    Jun 4, 2012 at 5:49
  • Thanks a lot. After enclosing it in try-catch, it worked like a charm.
    – Dilawar
    Jun 4, 2012 at 5:59
  • 3
    The 'invoke' used inside first invoke i.e. invoke(this, Integer.valueOf(10))); gives me compilation error that the invoke method is undefined. Oct 16, 2014 at 10:37
  • 1
    methodToFind will never be NULL, because a NoSuchMethodException will already be thrown.
    – Foumpie
    Dec 5, 2016 at 12:16
26

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

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.
  }
}
4
  • Thanks for the code. The main trouble is even if I have identify that a method getA does note exists, I need to write that function. For example if methodA exists then methodA(). It is giving compile time error since this method does not exits. How can I let the compilation goes on and make it a run-time check?
    – Dilawar
    Jun 4, 2012 at 5:37
  • 1
    @Dilawar, you should be perusing some reflection tutorials, because it appears you are going to need it a lot. Jun 4, 2012 at 5:46
  • I have updated the question. Please have a look. And you are right about my level of understanding of reflection.
    – Dilawar
    Jun 4, 2012 at 5:52
  • 1
    +1 for being accurate. I agree the question is not clear enough.
    – havexz
    Jun 4, 2012 at 6:03
12

With Spring:

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

If you use Spring Framework, the simplest way would be to use ReflectionUtils.findMethod() utility.

2

Another way is by using Java 8 stream:

  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().
        }
1

You can use Reflection in Java http://docs.oracle.com/javase/tutorial/reflect/index.html

or http://docs.oracle.com/javase/tutorial/reflect/member/methodType.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.