简体   繁体   中英

What's the proper way of declaring project constants in 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 ?

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 ?

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

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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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