【问题标题】:Is there any annotation to warn that subclasses shouldn't hide a static method in Java是否有任何注释警告子类不应隐藏 Java 中的静态方法
【发布时间】:2017-07-25 13:49:59
【问题描述】:

我有一个类,其中包含 Java 中的公共静态方法。 java中是否有任何注释来警告子类不要使用相同的方法签名(从而隐藏超类方法)。任何其他解决方法也可以。

【问题讨论】:

  • Eclipse(可能还有大多数主要的 IDE)对此发出警告。除此之外,还有像 PMD 这样的静态代码分析工具,您可以将其合并到构建过程中。
  • @litelite 你不能覆盖静态方法。
  • 你写了“......不要使用相同的方法名......” - 你的意思是你不仅要在子类方法隐藏超类方法时发出警告,而且在它 重载它(即不同的参数)?

标签: java inheritance annotations


【解决方案1】:

只需制作超类方法final:

class Foo {
    public static final void go() {}
}

class Bar extends Foo {
    public static void go() {};  // Error
}

Ideone Example

【讨论】:

  • 我误解了 final 关键字不适用于静态方法。现在想通了。谢谢。
【解决方案2】:

你不需要这样的注释,因为你试图做的事情不会编译......

在java中你不能覆盖静态方法


正如@thomas 建议的那样(+1 dafuer),您可以使用静态方法的可见性 示例:

public class Calculator {

    static int add(int a, int b) {
        System.out.println("a+b= " + (a + b));
        return a + b;
    }

    public static void main(String[] args) {

    }
}

然后

public class ScientificCalculator extends Calculator {

    public int add(int a, int b) {
        System.out.println("11111");
        return a + b;
    }

}

【讨论】:

  • 你不能覆盖它们,但你可以隐藏它们。
  • OP 希望收到有关此类情况的警告?
  • 他是这么写的:“java中是否有任何注解来警告子类不要使用相同的方法名(从而隐藏超类方法)”
【解决方案3】:

我不知道有任何这样的注释来标记方法的声明。但是,您可以从相反的方向进行处理。您可以查看它的用途,而不是关注方法声明。 -Xlint:all 将警告任何用途是否有问题。与父类中的静态方法具有相同签名的静态方法只会在从实例引用该方法而不是静态引用该方法时引起问题。考虑这个例子:

public class Foo {

  public static String getFoo(){
    return "foo";
  }
}

public class Bar extends Foo {

  public static void main(String[] args){

    Bar bar = new Bar();
    String s = bar.getFoo(); // Actually calls Foo.getFoo()
    System.out.println(s); // Prints "foo"

   }
}

在上面的代码中,我们通过Bar 的实例从Foo 引用了静态getFoo() 方法。 bar.getFoo() 行实际上从 Foo 调用静态方法。现在假设我们添加一个与Bar具有相同签名的静态方法:

public class Bar extends Foo {
   public static String getFoo(){
      return "bar";
   }

  public static void main(String[] args){

    Bar bar = new Bar();
    String s = bar.getFoo(); // Actually calls Bar.getFoo()
    System.out.println(s); // Prints "bar"

   }
}

这从Bar 中隐藏了Foo.getFoo() 方法,现在改为调用Bar.getFoo() 方法。在实际情况下,这几乎肯定会破坏Bar。如果您使用-Xlint:all 选项进行编译,那么您会收到以下消息:

warning: [static] static method should be qualified by type name, Foo, instead of by an expression

您在编译Bar 的第一个版本时会注意到这一点,您可以立即将其修复为String s = Foo.getFoo()。稍后当getFoo 也添加到Bar 时,原始代码仍然可以工作,因为它显式引用了Foo 中的方法。如果您总是通过引用声明它们的类来显式调用静态方法,那么在子类中拥有相同方法的唯一问题是它并不是最佳实践。也许也有一种标记声明的方法,但我会专注于确保正确使用静态方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 2012-09-04
    • 2012-11-07
    相关资源
    最近更新 更多