简体   繁体   English

在Java程序中对文本字符串进行硬编码的替代方法?

[英]Alternative practice for hard coding text strings in a Java program?

In my program I have lots of string and repeated strings. 在我的程序中,我有很多字符串和重复的字符串。 Is there a way to separate the text strings from the source code. 有没有一种方法可以将文本字符串与源代码分开。 I do not want to hardcode the string within my program. 我不想在程序中对字符串进行硬编码。

In PHP I used to have a file with list variables for each string. 在PHP中,我曾经有一个文件,其中包含每个字符串的列表变量。 But because Java is OOP I do not know how to implement the same idea. 但是因为Java是OOP,所以我不知道如何实现相同的想法。

My program is a command line program. 我的程序是命令行程序。

One other alternative is having properties file (key-value), same like how you did in PHP. 另一种选择是使用属性文件(键值),就像在PHP中一样。

Even though it is command line program you can still have properties file. 即使它是命令行程序,您仍然可以拥有属性文件。 You may pass file location as command argument (or) place your file relative to class and use relative path to access file. 您可以将文件位置作为命令参数传递(或)相对于类放置文件,并使用相对路径访问文件。

If your strings don't need to be changed by non-Java developers, you can simply put them all in a separate class, like this: 如果非Java开发人员不需要更改您的字符串,则可以将它们全部放在单独的类中,如下所示:

public final class Texts {
    public static final String MYSTR1 = "str1";
    public static final String MYSTR2 = "str2";
    ...
    private Texts() {} // Prevents instantiation
}

Doing so makes some maintaining tasks easier, for instance: 这样做使某些维护任务更加容易,例如:

  • You can refactor the constant name, so that all uses are automatically changed. 您可以重构常量名称,以便自动更改所有用途。
  • You can easely find who uses each constant. 您可以轻松找到谁使用每个常量。
  • You can quickly discover what is the constant's value, and you can navigate to it very quickly. 您可以快速发现什么是常量的值,并且可以非常快速地导航到该常量。

Use a statics class to hold your globals. 使用静态类来保存您的全局变量。

public class Statics
{
 public static final String GLOBAL_NAME = "Stuff";
 public static final int GLOBAL_INT = 9999;
}

And access it like this in your classes. 并在您的班级中访问它。

Statics.GLOBAL_NAME

If you are using Java 1.7 (SE 7), you can use java.util.Properties. 如果使用的是Java 1.7(SE 7),则可以使用java.util.Properties。 The java documentation provides a good explanation. Java文档提供了很好的解释。 Here is a code snippet: 这是一个代码片段:

String fileName = "/path/to/file/thePropertiesFileName.properties";
FileReader reader = new FileReader(fileName);
Properties prop = new Properties();
prop.load(reader);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM