[英]How to externalize the string for an error message in a custom exception class in Android
我有这堂课
public class InternetConnectionException extends RuntimeException {
int code = 0;
public InternetConnectionException(){
super("Internet connection is down");
}
public InternetConnectionException(String message){
super(message);
}
}
此错误消息不应进行硬编码。 应该将其外部化以提供不同的语言,因为抛出此异常时,消息将显示在屏幕上。 现在,是否有一种方法可以将其外部化为strings.xml
资源,还是应该更改设计? (即,抛出此异常时,只需在活动中引用字符串资源并显示已解析的值)
我认为,好的设计不应允许纯Java类(例如异常)知道Android框架的内部,但我可能是错的。
由于您不能直接访问string.xml,但是我可以想到一种方法来实现您要完成的任务。
这是一些代码来证明这个想法
AppApplication.java
public class AppApplication extends Application {
public static StringConstant STRING_CONSTANT;
@Override
public void onCreate() {
super.onCreate();
STRING_CONSTANT = new StringConstant(getBaseContext());
STRING_CONSTANT.build();
}
}
StringConstant.java
public class StringConstant {
private Context context;
public static String appName;
// declare other String variables
public StringConstant(Context context) {
this.context = context;
}
public void build(){
setAppName(context.getString(R.string.app_name));
// set other String variables
}
public static String getAppName() {
return appName;
}
public static void setAppName(String appName) {
StringConstant.appName = appName;
}
}
现在从另一个类访问字符串
public class InternetConnectionException extends RuntimeException {
int code = 0;
public InternetConnectionException(){
super(AppAplication.STRING_CONSTANT.getAppName());
}
public InternetConnectionException(String message){
super(message);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.