有点晚了,但我发现这个解决方案在我的项目中效果很好。它使用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