在 Java 中声明项目常量的正确方法是什么?

发布于 2024-12-10 06:43:01 字数 296 浏览 0 评论 0原文

对于 Java 开发人员来说,这似乎是一个愚蠢的问题,但是,我是 Java 新手,而且我的背景是低级 c 语言。 我曾经包含一个头文件,其中包含与我的项目相关的所有常量。 (通常是#define)。 我现在正在开发一个大型 Java 项目,我需要将一些常量设置为全局常量(它们适合多个类,并在项目的各个部分中使用),

这让我很难决定将其放在哪里它,我应该多次声明相同的常量,每个类一个吗?

很多框架,使用XML文件来声明常量&框架的定义(Hibernate、Log4J 等)在我的项目中使用这种技术是否明智?如果是这样,如何才能轻松完成?

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 ?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

故事和酒 2024-12-17 06:43:01

与许多事情一样,有很多方法可以做到。您不应该做的一件事是多次声明它们 - 这简直是愚蠢的。 :P

一切都必须在 Java 的类中,所以要么:

  1. 选择一个“主”类(假设我有一个名为“FTPServerApp”的项目 - 我可以将它们放在那里)
  2. 创建一个包含所有这些类的“Util”类

当您弄清楚将它们放在哪里,以这种方式声明它们:

public static final [type] [NAME_IN_ALL_CAPS] = [value];

这将使

  • 它们可用于您的所有项目代码,任何地方(public),
  • 在该类的所有实例中仅存在该值的一个副本( static
  • 它们无法更改(最终)。

用下划线分隔的 ALL_CAPS_FOR_CONSTANT_NAMES 是 Java 中的约定。

因此,如果这是在名为 FTPServerAPP 的类中声明的,并且您有一个名为 SERVICE_PORT 的常量,则它可能是:

public class FTPServerApp {
  public static final int SERVICE_PORT = 21;

  ...
}

...并且您可以从任何类访问它,像这样...

  FTPServerApp.SERVICE_PORT

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

Everything has to be in a class in Java, so either:

  1. Pick a "main" class (say I have a project called "FTPServerApp" - I could put them there)
  2. Create a "Util" class that contains all of them

When you figure out where to put them, declare them all this way:

public static final [type] [NAME_IN_ALL_CAPS] = [value];

This will

  • 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).

The ALL_CAPS_FOR_CONSTANT_NAMES, separated by underscores, is the convention in Java.

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
清秋悲枫 2024-12-17 06:43:01

查看枚举类型 (http://download.oracle.com/ javase/tutorial/java/javaOO/enum.html)它们应该提供一种提供常量的机制,而无需定义具体的类(或具有所需常量的接口,这是人们使用的另一种选择)。

我发现另一种有用的技术(类似于上面给出的 FTPServerApp 示例)是为任何子系统/组件/等定义一个上下文...它不仅保存该系统中组件所需的常量,而且可以保存您需要的任何状态。想要更加明显或者不希望单独的组件被保留。我相信这符合 GoF 模式之一,但自从我看过那本书以来已经很久了,我无法确定(而且我现在懒得去查它!)

Take a look at enumeration types (http://download.oracle.com/javase/tutorial/java/javaOO/enum.html) They are supposed to provide a mechanism to supply constants without defining a concrete class (or an Interface with the desired constants, as is another option that people use).

One other technique I find helpful (similar to the FTPServerApp example given above) is to define a Context for whatever subsystem/component/etc... that holds not only the constants needed by components in that system, but can hold any state that you want to make more visible or don't want individual components to hold. I believe this is along the lines of one of the GoF patterns, but it has been so long since I have looked at that book that I can't be certain (and I am too lazy to look it up right now!)

同展鸳鸯锦 2024-12-17 06:43:01

很老的问题。但这是我的回答,在杰弗伦特的回答之上添加了一些要点。
让我们假设您想要一个 MyConstant

  1. 将类设为 final (如果您希望扩展它,请忽略)
  2. 将成员变量设为 final static
    • 如果您希望将它们作为全局常量,请将它们标记为public
    • 如果仅在包中您可以将它们标记为受保护
  3. 将构造函数标记为 private。理想情况下,您不想创建此 Constant 类的多个实例,
  4. 请编写一个从主类调用的 static initialize() 方法。这是为了初始化所有对象成员变量
public final class MyConstants {
    
    public static final int CONSTANT_ONE = 10;
    private static final Map<String, String> DATA = new HashMap<>();

    public static void initialize() {
        DATA.put("RANDOM", "VALUE");
    }
    public enum color {
        red, blue;
    };

    private MyConstants() {
    }

    public static Map<String, String> getData() {
        return DATA;
    }
}
public class SomeOtherClass {

    public static void main(String args[]) {
        MyConstants.initialize();
        System.out.println(MyConstants.getData());
        System.out.println(MyConstants.CONSTANT_ONE);
    }
}

Very old question. but here's my Ans adding few point on top of jefflunt's ans.
Lets consider you want a MyConstant class

  1. Make the class final (if you want it to be extended, ignore)
  2. Make member variables final static
    • if you want these as a global constants mark them as public
    • if only at package you can mark them as protected
  3. Make constructor as private. Ideally you'd not want to create multiple instances of this Constant class
  4. Write a static initialize() method that you'd call from your main class. This is for the initialization of all object member variables
public final class MyConstants {
    
    public static final int CONSTANT_ONE = 10;
    private static final Map<String, String> DATA = new HashMap<>();

    public static void initialize() {
        DATA.put("RANDOM", "VALUE");
    }
    public enum color {
        red, blue;
    };

    private MyConstants() {
    }

    public static Map<String, String> getData() {
        return DATA;
    }
}
public class SomeOtherClass {

    public static void main(String args[]) {
        MyConstants.initialize();
        System.out.println(MyConstants.getData());
        System.out.println(MyConstants.CONSTANT_ONE);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文