问题描述
对于Java开发人员来说,这似乎是一个愚蠢的问题,但是,我是Java的新手,我的背景是c级以下的知识。
我曾经包括一个头文件,其中包含与我的项目相关的所有常量。 (通常是#define)。
我现在正在从事一个大型Java项目,我需要使一些常量成为全局常量(它们适合多个类,并在项目的各个部分中使用)
This may seems a silly question for Java developers, however, I'm new to Java, and my background is from low level c.I used to include an header file with all the constants that were relevant for my projects. (usually #define's).I'm working on a big Java project now, and there a few constants I need to make global (they fit in more than one class, and used in various parts of the project )
这让我很难决定将其放置在哪里,我是否应该多次声明相同的常量,每个类一次?
It makes it hard for me to decide where to put it, should I declare the same constant few times, one in each class ?
很多框架都使用XML文件声明常量&框架的定义(Hibernate,Log4J等)在我的项目中使用这种技术是否明智?如果是这样,如何轻松完成?
A lot of framework, uses XML files to declare constants & definitions for the framework (Hibernate, Log4J, etc.) Is it wise to use this kind of technique in my project ? if so, how can it be done easily ?
推荐答案
与很多事情一样,有很多方法可以做到这一点。您不应该做的一件事是多次声明它们-这简直是愚蠢的。 :P
As with many things, there are many ways to do it. One thing you should not do is declare them multiple times - that's just plain silly. :P
一切都必须放在Java类中,所以要么:
Everything has to be in a class in Java, so either:
- 选择一个主类(例如,我有一个名为 FTPServerApp的项目-我可以将它们放在那里)
- 创建一个包含所有它们的 Util类
弄清楚放置它们的位置时,请完全声明它们:
When you figure out where to put them, declare them all this way:
public static final [type] [NAME_IN_ALL_CAPS] = [value];
这将
- 使它们可用于任何地方的所有项目代码(
公共
) - 在所有实例中仅存在值的一个副本类(
static
) - 它们不能更改(
final
)
- make them available to all your project code, anywhere (
public
) - only one copy of the value exists across all instances of the class (
static
) - they cannot be changed (
final
).
ALL_CAPS_FOR_CONSTANT_NAMES
是Java中的约定。
The ALL_CAPS_FOR_CONSTANT_NAMES
, separated by underscores, is the convention in Java.
因此,如果在名为 FTPServerAPP
的类中声明了该变量,则您有一个名为<$ c $的常量。 c> SERVICE_PORT 可能是:
So, if this was declared in a class called FTPServerAPP
, and you had a constant called SERVICE_PORT
it might be:
public class FTPServerApp {
public static final int SERVICE_PORT = 21;
...
}
...可以从任何类访问它,就像这样...
...and you would access it, from any class, like this...
FTPServerApp.SERVICE_PORT
这篇关于用Java声明项目常量的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!