如何在Java中向父方法添加注释而无需覆盖它?

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

How to Add Annotations to Parent Method in Java Without Overriding It?

问题

In Java,如何在不更改方法主体的情况下向父方法添加注释?
例如:

public class ParentClass {
  public void someMethod() {
    System.out.println("Hello world");
  }
}

public class ChildClass extends ParentClass {
  // 在someMethod上添加@Deprecated注释,而不更改其主体
}

我需要保持方法不变,唯一的区别是现在它有一个注释。我该如何做?

我尝试过不包括方法主体,例如:

public class ChildClass extends ParentClass {
  @Override
  @Deprecated
  public void someMethod();
}

这不起作用。我也尝试过不使用@Override注释,但似乎它期望方法将具有主体。是否有一种方法只是添加注释而不更改其实际值?

英文:

In Java, how can I add an annotation to a parent method without changing the body of the method.
For example:

public class ParentClass {
  public void someMethod() {
    System.out.println("Hello world");
  }
}

public class ChildClass extends ParentClass {
  // Add the @Deprecated annotation to someMethod, without changing its body
}

I need the method to remain the same, but the only difference is now it has an annotation. How would I do this?

I have tried not including a body to the method, ie:

public class ChildClass extends ParentClass {
  @Override
  @Deprecated
  public void someMethod();
}

This doesn't work. I have also tried not using the @Override annotation, but it seems to expect that the method will have a body. Is there a way to just add the annotation without changing its actual value?

答案1

得分: 1

如果我理解正确,您可以这样做:

public class ChildClass extends ParentClass {
    @Override
    @Deprecated
    public void someMethod() {
        super.someMethod();
    }
}

然而,在这里,只有在声明为 ChildClass 的对象上调用 someMethod 才会被视为对已弃用方法的调用。在声明为 ParentClass 的对象上调用 someMethod(即使实际上是一个 ChildClass 对象)不会被视为已弃用的方法调用。

英文:

If I understood correctly, you can do it like that:

public class ChildClass extends ParentClass {
    @Override
    @Deprecated
    public void someMethod() {
        super.someMethod();
    }
}

However, here only calling someMethod on an object declared as ChildClass would be considered as call of a deprecated method. Calling someMethod on an object declared as ParentClass (even if it's actually an ChildClass object) wouldn't be seen as a deprecated method call.

答案2

得分: 0

你可以这样写:

public class ChildClass extends ParentClass {
  @Override
  @Deprecated
  public void someMethod(){
    super.someMethod();
  }
}
英文:

You can write like this

public class ChildClass extends ParentClass {
  @Override
  @Deprecated
  public void someMethod(){
    super.someMethod();
  }
}

huangapple
  • 本文由 发表于 2023年6月15日 02:58:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476763.html
匿名

发表评论

匿名网友

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

确定