使用Java系统属性的最佳实践 [英] Best Practice for Using Java System Properties

查看:92
本文介绍了使用Java系统属性的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的代码使用了很多系统属性,例如'java.io.tmpdir','user.home','user.name'等。我们没有为这些定义任何常量(也没有java I)思考)或处理它们的任何其他聪明的事情,因此它们在整个代码中散布着纯文本。

Our code uses a lot of system properties eg, 'java.io.tmpdir', 'user.home', 'user.name' etc. We do not have any constants defined for these anywhere (and neither does java I think) or any other clever thing for dealing with them so they are in plain text littered throughout the code.

String tempFolderPath = System.getProperty("java.io.tmpdir");

每个人如何使用系统属性?

How is everyone using system properties?

推荐答案

我会像处理代码中的任何其他字符串常量一样对待它,并为它定义一个常量变量。当然,在这种情况下,java.io.tmpdir不太可能改变,但你永远不会知道。 (我不是说Sun可能会改变java.io.tmpdir的含义,或者它指向的系统属性,但是你可能会改变你对你需要阅读的系统属性的想法。)

I would treat this just as any other String constant you have scattered throughout your code and define a constant variable for it. Granted, in this case "java.io.tmpdir" is unlikely to change, but you never know. (I don't mean that Sun might change the meaning of "java.io.tmpdir", or what system property it points to, but that you might change your mind about what system property you need to read.)

如果您只在一个类中使用特定属性,那么我将在该类中定义常量。

If you're only using a particular property within one class, then I'd define the constants right in that class.

private final String TEMPDIR = "java.io.tmpdir";

如果你在不同的类中使用相同的属性,你可能想要定义一个静态类你自己掌握最经常使用的常数。

If you're using the same properties in different classes, you may want to define an static class of your own to hold the constants you use most often.

public final Class Prop {
    public static final String TEMPDIR = "java.io.tmpdir";
    ...
}

然后,您需要使用该常量只需使用

Then, everywhere you need to use that constant just call it using

System.getProperty(Prop.TEMPDIR);

这篇关于使用Java系统属性的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆