Question

Is it possible to use annotations to create multiple versions of an API?

I've got a target API that needs implementing, but it has grown in time, and I would like to support multiple levels - if possible in the same branch. I've already thought about splitting up the API and proxy it to implementation library, but that still requires a lot of code to keep synchronized.

So you would create code like:

@Since("1.2") <- only created when 1.2 or higher
public interface InNewerAPI {

    @Since("1.3") <- only compiled when 1.3 or higher
    public void methodInEvenNewerAPI();

}

Of course I could also use a preprocessor for this, but I would like to avoid pre-processors for Java code.

Are there any drawbacks to this approach (such as loosing argument names prior to 1.8)?

Note that I need support for interfaces and classes, including abstract and inner classes. Methods and constants need to be versioned as well.

Was it helpful?

Solution

OK, I think that you can really use annotations to mark ranges of versions that should expose the API. For example if method foo() was introduced in version 1.1. and deprecated in version 1.5 you can mark it as following:

class MyApiImpl { @Since("1.2") @DeprecateAt("1.4") @Until("1.5") foo(); }

Then you can automatically generate interface interface MyApi according to client version:

  1. for client prior version 1.2 this method will not be included into the interface.
  2. for client between versions 1.2 and 1.4 it will be included
  3. for client version 1.4 it will be included but marked as @Deprecated
  4. it will not be included for clients after 1.5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top