简体   繁体   English

如何从Java构建中排除带注释的定义?

[英]How can I exclude annotated definition from build in java?

I am building an Android app. 我正在构建一个Android应用程序。 Now, I have a source code for API #1, I should get it adapted for API #2. 现在,我有API#1的源代码,我应该将其改编为API#2。 Then I will publish the both versions for API #1 and API #2 in different packages. 然后,我将在不同的程序包中发布API#1和API#2的两个版本。 I can't use something like values-en, because both versions can be used worldwide. 我不能使用values-en之类的东西,因为这两个版本均可在全球范围内使用。 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. 由于新版本将使用相同的UI和DB逻辑,并且(因为现在的代码是错误的),我不想分离代码。 If i were coding in c or c++, I must use #ifdef and Makefile. 如果我使用C或C ++进行编码,则必须使用#ifdef和Makefile。 However, I'm in Java. 但是,我在Java中。 It's possible to run the API-dependent code by determining the package name in runtime, but it's somewhat weird. 可以通过在运行时确定包名称来运行与API相关的代码,但这有点奇怪。

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: 要创建Api实例,请使用工厂类:

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. 在所有其他地方,您仅引用Api接口和ApiFactory类。 Use it like that: 像这样使用它:

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

A more advanced solution would be to use dependency injection . 一个更高级的解决方案是使用依赖注入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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