【问题标题】:How do I call a method of same name from an enclosing outer class as the one being implemented in an anonymous class?如何从封闭的外部类调用与匿名类中实现的方法同名的方法?
【发布时间】:2021-05-05 11:08:38
【问题描述】:

我正在使用匿名类实现一个接口,该类将预定义的文件夹路径作为字符串返回,并且需要一个斜杠。封闭对象的类已经将其实现为getDataFolder(),但返回一个File 对象。这很好,除了我正在实现的方法具有相同的名称......

如果我这样实现它,那么我会得到一个 stackoverflow 错误,因为实现的方法试图调用自身而不是外部类方法。

resourceManager = new PluginResourceManager(this) {
   @Override
   public String getDataFolder()
      throws IOException
   {
      return getDataFolder() + java.io.File.separator;
   }
};

外部类的方法在作用域内,但不直接被匿名类继承,所以我不能在这里简单地使用super

如何从这个匿名内部类方法的外部类中显式调用我想要的方法?

【问题讨论】:

  • “父方法”到底是什么意思?如果您可以提供minimal reproducible example,那将更容易为您提供帮助。
  • 你是说 OuterClass.this 吗?
  • 我在写完这篇文章后意识到我使用了错误的术语,并在编辑中更正了这一点。它是我试图调用的封闭外部类的方法,而不是我正在内联定义的匿名类(本身是一个接口)的父类的方法。

标签: java stack-overflow inner-classes anonymous-class


【解决方案1】:

如果封闭类中的方法是非静态的,那么这样调用它:

resourceManager = new PluginResourceManager(this) {
   @Override
   public String getDataFolder()
      throws IOException
   {
      return EnclosingClassName.this.getDataFolder() + java.io.File.separator;
   }
};

如果方法是静态的,那就简单一点:

resourceManager = new PluginResourceManager(this) {
   @Override
   public String getDataFolder()
      throws IOException
   {
      return EnclosingClassName.getDataFolder() + java.io.File.separator;
   }
};

【讨论】:

    猜你喜欢
    • 2021-04-30
    • 2019-03-16
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多