具有具体化泛型的内联函数在后台服务中使用时抛出非法类型变量引用异常

如何解决具有具体化泛型的内联函数在后台服务中使用时抛出非法类型变量引用异常

我有一个使用具体化泛型的内联函数,如下所示。它在伴随对象内,因此是静态的:

inline fun <reified T> getListFromPreferences(preferences : SharedPreferences,key : String)
        : MutableList<T> {
            return try {
                val listAsstring = preferences.getString(key,"")
                val type: Type = object : Typetoken<List<T>>() {}.type
                val gson = SMSApi.gson
                gson.fromJson<ArrayList<T>>(listAsstring,type)
                        ?: ArrayList()
            }catch(exception: JsonSyntaxException) {
                ArrayList()
            }
        }

当我使用仪器测试对其进行测试以及在应用程序本身中使用它时,它运行得非常好。但是,我在后台服务调用函数时,抛出了致命异常,说是非法类型变量引用,退出app:

E/AndroidRuntime: FATAL EXCEPTION: Thread-10 
    Process: example.app,PID: 20728 
    java.lang.AssertionError: illegal type variable reference 
        at libcore.reflect.TypeVariableImpl.resolve(TypeVariableImpl.java:111) 
        at libcore.reflect.TypeVariableImpl.getGenericDeclaration(TypeVariableImpl.java:125) 
        at libcore.reflect.TypeVariableImpl.hashCode(TypeVariableImpl.java:47) 
        at com.google.gson.internal.$Gson$Types$WildcardTypeImpl.hashCode($Gson$Types.java:595) 
        at java.util.Arrays.hashCode(Arrays.java:4074) 
        at com.google.gson.internal.$Gson$Types$ParameterizedTypeImpl.hashCode($Gson$Types.java:502) 
        at com.google.gson.reflect.Typetoken.<init>(Typetoken.java:64) 
        at example.app.NotificationService$remoteNotificationReceived$$inlined$let$lambda$1$1.<init>(PreferenceHelper.kt:16) 
        at example.app.NotificationService$remoteNotificationReceived$$inlined$let$lambda$1.run(NotificationService.kt:63) 
        at java.lang.Thread.run(Thread.java:764)
inline fun <reified T> getListFromPreferences(preferences : SharedPreferences,type)
                        ?: ArrayList()
            }catch(exception: JsonSyntaxException) {
                ArrayList()
            }
        }

后台服务是实现Onesignal的OSRemoteNotificationReceivedHandler的NotificationService。该函数在 onNotificationReceived() 方法中抛出异常。 有什么我不明白的原因,为什么在应用程序(前台)中内联很好,但在后台抛出异常?或者有什么办法可以解决这个问题?

编辑: 共享通知服务,调用它:

class NotificationService : Onesignal.OSRemoteNotificationReceivedHandler {
    override fun remoteNotificationReceived(context: Context?,notificationReceivedEvent: OSNotificationReceivedEvent?) {
        notificationReceivedEvent?.let {
            val data = notificationReceivedEvent.notification.additionalData
            if(context != null) {
                //Fetch some vals
                Thread {
                    val result = //Insert data in db
                    //-1 will be returned,for rows that are not inserted.
                    //Rows will not be inserted,if they hurt a unique constraint.
                    //Therefore the following code should only be executed,when it is inserted.
                    if(result[0]!=-1L) {
                    //Get preferences,create item    
                    val list = PreferenceHelper
                            .getListFromPreferences<MessageAckNowledgement> 
                        (preferences,App.ACKNowLEDGE_IDS) -> throws error
                    list.add(ackNowledgeMessage)
                    PreferenceHelper.setListInPreferences(preferences,App.ACKNowLEDGE_IDS,list)
                    //Do some more stuff
                    }
                }.start()
            }
            Log.d("NotificationService",data.toString())          
  notificationReceivedEvent.complete(notificationReceivedEvent.notification)
        }
    }
}

解决方法

我不确定上面的代码有什么问题,它需要共享更多的代码,但是 Kotlin 有一种获取 Type 令牌的本机方式。只需替换:

object : TypeToken<List<T>>() {}.type

与:

typeOf<List<T>>().javaType

由于 typeOf() 仍处于试验阶段,您需要使用以下内容注释您的函数:@OptIn(ExperimentalStdlibApi::class)。我已经使用它一段时间了,从来没有出现过任何问题,所以我想它使用起来非常安全,至少在 JVM 上是这样。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?