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

查看:33
本文介绍了使用 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?

推荐答案

我会像对待分散在整个代码中的任何其他 String 常量一样对待它,并为其定义一个常量变量.当然,在这种情况下,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天全站免登陆