简体   繁体   English

调用层次结构中较高级别的类的重写的受保护方法

[英]Calling the overridden protected method of a class higher up in the hierarchy

Consider the following classes in Java 考虑以下Java类

class A
{
   protected void methodA()
   {
      System.out.println("methodA() in A");
   }

}

class B extends A
{
    protected void methodA() // overrides methodA()
    {
        System.out.println("methodA() in B");
    }

    protected void methodB()
    {
    }
}

public class C extends B // needs the functionality of methodB()
{
    public void methodC()
    {
        methodA(); // prints "methodA() in B"
    }
}

How do I call the methodA() in a from methodC() in class C? 我如何在类C的methodC()中调用methodA()? Is that possible? 那可能吗?

You have a few options. 您有几种选择。 If the source code for class B is available, then modify class B. If you don't have the source code, consider injecting code into class B's methodA(). 如果提供了类B的源代码,则修改类B。如果没有源代码,请考虑将代码注入到类B的methodA()中。 AspectJ can insert code into an existing Java binary. AspectJ可以将代码插入现有的Java二进制文件中。

Change Class B 变更B级

package com.wms.test;

public class A {
  public A() {
  }

  protected void methodA() {
    System.out.println( "A::methodA" );
  }
}

package com.wms.test;

public class B extends A {
  public B() {
  }

  protected void methodA() {
    if( superA() ) {
      super.methodA();
    }
    else {
      System.out.println( "B::methodA" );
    }
  }

  protected void methodB() {
    System.out.println( "B::methodB" );
  }

  protected boolean superA() {
    return false;
  }
}

package com.wms.test;

public class C extends B {
  public C() {
  }

  protected void methodC() {
    methodA();
  }

  protected boolean superA() {
    return true;
  }

  public static void main( String args[] ) {
    C c = new C();

    c.methodC();
  }
}

Then: 然后:

$ javac com/wms/test/*.java
  $ java com.wms.test.C
  A::methodA

The following does not work: 以下内容不起作用:

  protected void methodC() {
    ((A)this).methodA();
  }

This looks similar to you're problem 看起来类似于您的问题

Can you edit B and add a function that calls super.MethodA() ? 您可以编辑B并添加一个调用super.MethodA()的函数吗? then call that in C? 然后在C中调用它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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