[英]How can I have a constant variable common to all classes in a package?
I want a constant variable to be common to all classes in a package. 我希望一个常量变量对于包中的所有类是通用的。 Is there a way I can do this without making an interface just with the one definition in it, and making every class implement that?
有没有办法我可以做到这一点,而不是只使用其中的一个定义接口,并使每个类实现它?
In Java, all constants have to reside in a type (class or interface). 在Java中,所有常量都必须驻留在类型(类或接口)中。 But you don't have to implement an interface to use a constant declared inside.
但是您不必实现接口来使用在内部声明的常量。
You can try by putting something like this in your package: 你可以尝试在你的包中加入这样的东西:
interface Constants {
static final String CONSTANT = "CONTANT";
}
and then, using it like this: 然后,像这样使用它:
String myVar = Constants.CONSTANT;
This way, you still have your interface, but no classes implement it. 这样,你仍然有你的界面,但没有类实现它。
Generally applications have a "Constants" class or interface that holds all constants. 通常,应用程序具有“常量”类或包含所有常量的接口。
I generally to to group constants into logical classes. 我通常将常量分组为逻辑类。 For instance if there can be two kinds of employees, regular and contract:
例如,如果有两种员工,常规和合同:
class EmployeeType
{
public static final String REGULAR = "regular";
public static final String CONTRACT = "contract";
}
and use it as EmployeeType.REGULAR
并将其用作
EmployeeType.REGULAR
If the constants cannot be grouped this way, have a separate class/interface to hold these. 如果常量不能以这种方式分组,请使用单独的类/接口来保存它们。
class Constants
{
public static final String APPLICATION_DOMAIN = 'domain';
}
You need not extend/implement this class interface to use the values. 您无需扩展/实现此类接口即可使用这些值。 The constants will generally be declared
public static final
, you can access them directly : Constants.APPLICATION_DOMAIN
常量通常被声明为
public static final
,您可以直接访问它们: Constants.APPLICATION_DOMAIN
Use a package private class: 使用包私有类:
class Constants{
public static final int MY_VALUE = 1234;
}
This can only be accessed by classes from the same package: 这只能通过同一个包中的类访问:
int val = Constants.MY_VALUE;
You can do this in various ways: 您可以通过各种方式执行此操作:
public static final
attributes of each constants.` public static final
属性 =
operator) each declared on a newline. =
运算符分隔)。 Here's a tutorial on how to create and use properties file. 似乎是一个很好的候选人在我的财产文件中输入。
您可以使用抽象类作为该包中每个impl的基类。
You could make a special (static) class with just this variable. 你可以用这个变量创建一个特殊的(静态)类。 Later you can add other constants or whatever you need to that class.
稍后您可以添加其他常量或您需要的任何类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.