如何在Java中从多个接口访问常量?

huangapple go评论58阅读模式
英文:

How to access a constant from multiple interfaces in java?

问题

我有两个接口,它们都使用这两个常量

static final File UPLOAD_DIR = new File(System.getProperty("catalina.home") + File.separator + "uploads");
static final String UPLOAD_DIR_ABSOLUTE_PATH = UPLOAD_DIR.getAbsolutePath() + File.separator;

我如何在不在两个接口中初始化它们的情况下访问它们?我应该创建一个最顶层的接口吗(但是这两个接口没有共享任何方法)?

英文:

I have two interfaces which both use these two constants

static final File UPLOAD_DIR = new File(System.getProperty("catalina.home") + File.separator + "uploads");
static final String UPLOAD_DIR_ABSOLUTE_PATH = UPLOAD_DIR.getAbsolutePath() + File.separator;

How can I access them without initializing them in both interfaces? Do I create a topmost interface (but these two interfaces do not share any methods)?

答案1

得分: 1

你可以这样做:

public interface MyConstants {
    public static final File UPLOAD_DIR = 
        new File(System.getProperty("catalina.home") +
                 File.separator + "uploads");
    public static final String UPLOAD_DIR_ABSOLUTE_PATH = 
        UPLOAD_DIR.getAbsolutePath() + File.separator;
}

public interface InterfaceA extends MyConstants {
    ...
}

public interface InterfaceB extends MyConstants {
    ...
}

public class Test implements InterfaceA, InterfaceB {
    // 使用 UPLOAD_DIR
}

需要注意的是,一个类通过多条路径继承接口的常量声明在 Java 中是合法的。

(关于在接口常量声明中是否使用修饰符,这是个人品味或风格问题。根据 Java 语言规范(JLS),它们隐式publicstaticfinal;参见 JLS 9.3。)

但仅仅因为你可以做某事,并不一定意味着你应该这么做。有些人认为仅包含常量的接口是一种反模式。

阅读以下内容并自行判断:

英文:

You could do this:

public interface MyConstants {
    public static final File UPLOAD_DIR = 
        new File(System.getProperty("catalina.home") +
                 File.separator + "uploads");
    public static final String UPLOAD_DIR_ABSOLUTE_PATH = 
        UPLOAD_DIR.getAbsolutePath() + File.separator;
}

public interface InterfaceA extends MyConstants {
    ...
}

public interface InterfaceB extends MyConstants {
    ...
}

public class Test implements InterfaceA, InterfaceB {
    // Use UPLOAD_DIR
}

Note that it is legal Java for a class to inherit an interface's constant declarations via multiple routes.

(It is a matter of personal taste or style whether you used modifiers in interface constant declarations. According to the JLS, they are implicitly public static final; see JLS 9.3.)


But just because you can do something doesn't necessarily mean that you should do it. Some people consider declaring an interface that consists solely of constants to be an Anti-pattern.

Read the following and make up your own mind:

huangapple
  • 本文由 发表于 2020年9月6日 02:38:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63757331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定