有點晚了,但我發現這個解決方案在我的項目中效果很好。它使用Android Application
類來設置覆蓋庫配置的單例配置實例。
Config
和ConfigInstance
下面是在庫中。
public final class Config {
public static final boolean VAL;
private Config() {}
static {
// this will be overridden by previous calls to
// ConfigInstance.getInstance()
final ConfigInstance confInstance = ConfigInstance.getInstance(ConfigInstance.DEFAULT_VAL);
VAL = confInstance.val;
}
}
// Singleton helper class, be sure not to reference the Config class
// here so that it is not loaded
public final class ConfigInstance {
private static volatile ConfigInstance instance = null;
static final boolean DEFAULT_VAL = false;
public final boolean val;
private ConfigInstance(final boolean val) {
this.val = val;
}
// thread safe singleton generator
public static ConfigInstance getInstance(final boolean val) {
ConfigInstance result = instance;
if (result == null) { // 1st check no lock
synchronized (ConfigInstance.class) {
result = instance;
if (result == null) { // 2nd check with lock
instance = result = new ConfigInstance(val);
}
}
}
return result;
}
}
添加下面的類的每個上級項目,確保設置在清單中的<application>
標籤中的「名稱」字段。
public class ApplicationWrapper extends Application {
static {
// this will set the singleton ConfigInstance first, ie. before
// the library static block is executed; forcing it to use the
// values here
ConfigInstance.getInstance(true);
}
}
有了這個,Config.VAL
將在項目設置爲true
。
您可以私有化布爾引用並添加一個公共方法,根據需要返回true/false。應用程序版本B可以覆蓋以返回false。 – Swati 2011-05-17 20:37:02
如果它不是常量,不要稱之爲常量。這聽起來更像一個配置(有很多方法來創建/使用配置)。 – 2011-05-17 20:39:15
@Swati,我想到了,但它是需要布爾值的庫代碼,所以它永遠不會看到覆蓋。 – CodeFusionMobile 2011-05-17 20:41:52