嗨,我有20个字符串,除了类名之外,每个字符串都有相同的包结构。这些字符串需要根据需要传递给方法。请参考以下代码:
public static final String RECENT_MSG_ = "com.foo.xxs.RecentMessage";
public static final String PROJ_ = "com.foo.xxs.Proj";
public static final String FORECAST = "com.foo.xxs.Forecase";
public static final String REQUEST = "com.foo.xxs.Request";
public static final String UNAPPROVED = "com.foo.xxs.UnApproved";
public static final String UNPOSTED = "com.foo.xxs.Unposeted";
public static final String VACANT = "com.foo.xxs.Vacant";
public static final String ORG_VIOL = "com.foo.xxs.OrgViolation";
public static final String ORG_WARN = "com.foo.xxs.OrgWarning";
public static final String EMP_VIOL = "com.foo.xxs.EmpViolation";
public static final String EMP_WARN = "com.foo.xxs.EmpWarning";
public static final String TS_WARN = "com.foo.xxs.TSWarn";
public static final String TS_VIOL = "com.foo.xxs.TSViolation";
public static final String AGE_GROUP = "com.foo.xxs.AgeGroup";
private void rescheduleTasks(long _taskType,String value)
{
if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(RECENT_MSG_)==null))
{
// do something
}
}也可以按如下方式执行此操作:
public static final String RECENT_MSG_ = "RecentMessage";
public static final String PACK ="com.foo.xxs."并像这样连接字符串:
if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(PACK+RECENT_MSG_)==null))哪一个更好?
发布于 2010-08-19 14:56:32
它们将具有相同的性能-连接将在编译时执行,而不是在执行时执行,因为两部分都是常量。诚然,在原始版本中,常量池中的字符串会更少-但这不太可能有什么不同。
你觉得哪一个更具可读性?我不能说这对我有多大好处--我不喜欢重复第一种形式,但同样,我也不确定我会不会想要连接所有地方。
另一种选择是:
public static final String PACK = "com.foo.xxs."
public static final String RECENT_MSG_ = PACK + "RecentMessage";etc -所以你在常量声明的地方执行连接。然后,您可以根据第一个代码片段在代码中使用RECENT_MSG_,但根据第二个代码片段避免"com.foo.xxs“重复。
编辑:您可能需要考虑的另一个选项是使用枚举。
发布于 2010-08-19 15:03:00
我会选择第一个版本,你只是让读者更容易立即看到字符串的含义以及你引用的是什么类。此外,如果您希望引入来自不同名称空间的类,您将能够做到这一点。
相比之下,第二个版本引入了一些需要读者首先解释的逻辑。
如果您选择第二个版本,请改用Jon的替代方案,这样至少您仍然可以选择从其他名称空间引入类。
https://stackoverflow.com/questions/3519405
复制相似问题