首页 > 解决方案 > 使用 trait 从外部类调用嵌套静态类内部的方法

问题描述

我在两个不同的 A、B 类中有一个静态类“Inner”和一个嵌套静态类“Deeper”。'Inner' 类实现了具有称为 ping() 的方法的特征 C。我想从 ping() 方法中执行方法 hello()(属于 Deeper),每次我都会根据调用该特征的类获得“Hello A”或“Hello B”。这就是我写的(我正在使用katalon-studio):

public class A
{
  static class Inner implements C{
     static class Deeper{ 
         static void hello(){ println 'Hello A'}
    }
  }
}
public class B
{
  static class Inner implements C{
     static class Deeper{ 
         static void hello(){ println 'Hello B'}
    }
  }
}
public static trait C {
     static void ping() {
          this.Deeper.hello()
     }
}

A.Inner.ping()
B.Inner.ping()

我收到以下错误:

2018 年 8 月 17 日下午 4:46:57 - [错误] - 测试用例/V2/常规/草稿失败,因为没有为测试用例定义变量“更深”。

标签: groovykatalon-studio

解决方案


找不到这个问题的答案。然而,使用非静态类,这可以实现如下:

public class A{
   class Inner implements C{
      A.Inner.Deeper d = new A.Inner.Deeper()
      class Deeper { 
          void hello(){ 
             println 'Hello A'  
          }
      }
   }
}
public class B{
   class Inner implements C{
      B.Inner.Deeper d = new B.Inner.Deeper()
      class Deeper{ 
          void hello(){ 
             println 'Hello B' 
          }
      }
   }
}

public trait C{
      public void ping(){
         this.d.hello()
      }
}

new A.Inner().ping()
new B.Inner().ping()

推荐阅读