简体   繁体   中英

How can I exclude annotated definition from build in java?

I am building an Android app. Now, I have a source code for API #1, I should get it adapted for API #2. Then I will publish the both versions for API #1 and API #2 in different packages. I can't use something like values-en, because both versions can be used worldwide. Also, the user may not have choice.

As the new version will use same UI and DB logic, (and because now the code is erroneous,) I don't want to separate the code. If i were coding in c or c++, I must use #ifdef and Makefile. However, I'm in Java. It's possible to run the API-dependent code by determining the package name in runtime, but it's somewhat weird.

I think I can use annotations. What I expect is:

package foo.app;
public class API {
    public boolean prepare() { ... }
    @TargetPlatform(1)
    public void open() { ... }
    @TargetPlatform(2)
    public void open() { ... }
}

and use only one of them. Also, this is good:

package foo.app;
public class R {
    @TargetPlatform(1) com.example.foo.app.R R;
    @TargetPlatform(2) net.example.foo.app.R R;
}

Just defining an annotation is simple. What I don't know is, how can I exclude unused duplicates from build or execution, or so on? If the work can be done in this way, I can do anything.

You cannot use annotations for that.

It would be better to hide the implementation specific classes behind an interface.

public interface Api {
  boolean prepare();
  void open();
}

To create a Api instance use a factory class:

public class ApiFactory {
  public static Api createApi() {
    if(isTargetPlatform1()) 
      return new com.example.foo.app.Api();
    else
      return new net.example.foo.app.Api();
  }

  private boolean isTargetPlatform1() {
    // determine the current platform, e.g. by reading a configuration file
  }
}

In all other places you only refer to the Api interface and ApiFactory class. Use it like that:

Api api = ApiFactory.createApi();
api.open();
// ...

A more advanced solution would be to use dependency injection .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM