【问题标题】:Problems inheriting inner java class继承内部java类的问题
【发布时间】:2020-11-17 04:12:48
【问题描述】:

我正在使用 Kotlin 创建一个 android 动态壁纸。这需要一个扩展 WallpaperService 的类,该类包含一个扩展 WallpaperService.Engine 的内部类。

所以我写了这个:

import android.service.wallpaper.WallpaperService
import android.service.wallpaper.WallpaperService.Engine

public class MyWallpaperService : WallpaperService() {

    override fun onCreateEngine(): Engine = MyEngine()

    private inner class MyEngine : Engine() {

    }
}

问题是我在编译时遇到以下 2 个错误:

Error:java.lang.RuntimeException: Error generating constructors of class MyEngine with kind IMPLEMENTATION 

Error:java.lang.UnsupportedOperationException: Don't know how to generate outer expression for lazy class MyWallpaperService

我无法弄清楚为什么会发生这种情况,因此我们将不胜感激。

【问题讨论】:

    标签: android kotlin


    【解决方案1】:

    我发现的最佳解决方案是使用中间 Java 类:

    public class Intermediate extends WallpaperService.Engine {
        public Intermediate(WatchfaceService outer) {
            outer.super();
        }
    }
    

    那么 Kotlin WallpaperService 中的内部类应该继承 Intermediate,将外部类作为参数传递。

    public class MyWallpaperService : WallpaperService() {
        override fun onCreateEngine(): Engine = MyEngine()
    ​
        private inner class MyEngine : Intermediate(this) {
        }
    }
    

    【讨论】:

      【解决方案2】:

      KT-6727

      您可以尝试以下解决方法:

      private inner class MyEngine : super.Engine() {
      }
      

      【讨论】:

      【解决方案3】:

      对于其他搜索此问题的人,我想指出这现在在 Kotlin 中有效 (我使用的是 1.4.10 我还没有验证修复了哪个版本)。

      要记住的关键是必须将引擎标记为内部类,否则 Kotlin 将不知道如何引用被继承的引擎。

      class SampleService : WallpaperService() {
      
      // region override
      override fun onCreateEngine(): Engine {
      
          return IntermediateEngine()
      }
      
      // endregion
      
      // region inner class
      
      inner class IntermediateEngine() : Engine() {
      
          
      }
      
      // endregion
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-26
        • 1970-01-01
        • 1970-01-01
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-15
        相关资源
        最近更新 更多