根据使用库 [Android-Java] 的应用程序更改库中定义的常量变量

Change constant variables defined in a library depending on the application that uses the library [Android-Java]

我有一个 android 库项目,其中包含 2 个 Android 项目的许多通用代码。

在我的图书馆项目中,我有一个 ContentProvider 实现和一个 Service 实现。

计划在每个项目中扩展这2个class,并在Manifest文件中单独指定它们。

但我有一个 class 常量如下,

public class LiquidContentProviderContract {

    public static String CONTENT_AUTHORITY;

    public static String ANDROID_APPLICATION_TABLE = "androidapp";

    public static Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

    public static Uri CONTENT_URI_ANDROID_APPLICATION =
            BASE_CONTENT_URI.buildUpon().appendPath(ANDROID_APPLICATION_TABLE).build();

}

但是我想根据我要使用这个库的应用程序更改这个 CONTENT_AUTHORITY 变量。

最好的方法是什么?支持这种实现的常见设计模式是什么。

我尝试了以下方法,看看我是否至少可以让这个东西工作,

public class Foo{

     public static void main(String []args){

        Newfile.te = "Nothing";

        System.out.println(Newfile.te);

        System.out.println(Newfile.tf);

     }
}

public class Newfile{

  public static String te = "Mango";

  public static String tf= Newfile.te + " Eating";

}

输出是,

Nothing
Mango Eating

但我很期待,

Nothing
Nothing Eating

谢谢

你得到输出的原因是静态初始值设定项在加载 class 时计算一次。当 class 加载时,te 是 mango,因此它将 tf 分配给 Mango Eating,并且永远不会重新计算。 class 什么时候加载?就在第一次使用之前。你想做的事永远行不通。

老实说,从您的需求来看,您应该重新考虑您的架构 - 您想要的听起来应该是库的参数而不是静态值。

我不认为这种设计明智的方法是个好主意。但是因为它是 Android,所以有很多与框架相关的 classes 限制了向 class 中注入东西。在这种情况下,我使用这种技术。

public class Foo {
    public static void main(String []args) {
        Newfile.te = "Nothing";
        System.out.println(Newfile.te);
        System.out.println(Newfile.getTf());
    }
}

public class Newfile {
    public static String te = "Mango";

    // instead of using this public static String tf= Newfile.te + " Eating";

    public static String getTf() {
        return Newfile.te + " Eating";
    }
}