David Rekowski's random stuff

Determine an API difference using reflection


Find out a specific API's version by examining whether a new method is available.


java, reflection, api, jax-ws

How to do it

Imagine your application requires for one reason or another a specific version of a library. Java provides the Reflection API to - among other things - examine classes. E.g. you can find out, whether a specific method is available.

Between JAX WS 2.1 and JAX WS 2.2 some changes were introduced, including a new constructor Service( wsdlDocumentLocation, javax.xml.namespace.QName serviceName, WebServiceFeature... features) (see API reference). We can thus check, whether a constructor with the given parameters exists.

package info.rekowski; import javax.xml.namespace.QName; import; import; import; /** * This program demonstrates how to determine an API difference by means of reflection. * In this case, we examine a difference between JAX WS 2.1 and JAX WS 2.2: The class * gained a new constructor with a third argument. */ public class ApiDifference { public static void main(String[] args) { try { Service.class.getDeclaredConstructor( URL.class, QName.class, WebServiceFeature[].class ); System.out.println("JAX WS 2.2"); } catch (NoSuchMethodException e) { System.out.println("JAX WS 2.1"); } } }

You can use getDeclaredMethod(String name, Class<?> ... parameterTypes) if you want to look at a specific method. Note, that you pass the parameter classes, not specific objects.