【发布时间】:2018-06-22 14:18:36
【问题描述】:
TL;DR:如何正确使用带有 Firebase DataSnapshot.getValue() 的泛型类?
用例:我想使用 Firebase 为我的所有实体(其中一堆)实现一个通用远程数据源类。在收听数据更改时,我想从 datasnapshot 中获取值作为 E 类型的对象(其类型在其他地方确定),但我不知道它是否可以通过 Firebase 查询实现,如下所示:
public class GenRemoteDataSource<E extends SomeClass>
{
//...
public void onDataChange(DataSnapshot dataSnapshot)
{
E item = (E) dataSnapshot.getValue(); // <- unchecked cast and it doesn't work
items.add(item);
}
}
例如,我有一个扩展 SomeClass 的 Foo 类,这个 GenRemoteDataSource 与 Foo 类的实现将是:
public class Foo extends SomeClass{}
public class FooRemoteDataSource extends GenRemoteDataSource<Foo>
{
//...
}
但 Firebase 会引发运行时错误,因为它不会将 getValue() 转换为 Foo,而是尝试将 value 转换为上限 SomeClass。我很困惑为什么会发生这种情况:
Java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.app.SomeClass
请告知我应该如何使用 Type-safety (No unchecked cast) 来做到这一点。谢谢。
编辑下面的东西被证明是无关紧要的,见GenericTypeIndicator
编辑 我也尝试过(盲目且值得一试)GenericTypeIndicator,
GenericTypeIndicator<E> mTypeIndicator = new GenericTypeIndicator<>();
E item = dataSnapshot.getValue(mTypeIndicator);
但它反而会吐出以下运行时错误。
com.google.firebase.database.DatabaseException: Not a direct subclass of GenericTypeIndicator: class java.lang.Object
【问题讨论】:
标签: java generics firebase-realtime-database