【问题标题】:Saving a Firestore object throws InvocationTargetException error保存 Firestore 对象会引发 InvocationTargetException 错误
【发布时间】:2018-07-31 10:50:45
【问题描述】:

我花了大约一个小时来调试这个问题,所以我想知道是否有人能够解释这里发生了什么。

我正在尝试在 Android(在 Kotlin 中)上保存一个 Firestore 自定义对象。这是一个简化版本 -

class MockTransaction {

    val endpoint: String = "mockTransactions"

    var fromAddress: String = ""
    var toAddress: String = ""
    var amount: Double = 0.0

    constructor() {}

    constructor(from: String, to: String, amount: Double) {
        this.fromAddress = from
        this.toAddress = to
        this.amount = amount
    }

    fun isValid(): Boolean {
        return true
    }

    fun save() {
        val db = FirebaseFirestore.getInstance()
        db.collection(endpoint).add(this).addOnCompleteListener {
            Log.d("TX", it.isSuccessful.toString() )
            Log.d("TX", it.exception.toString())
        }
    }

}

val tx = MockTransaction("Alice", "Bob", 100.0)
tx.save()

现在,如果我更改 isValid 函数以抛出异常,像这样

fun isValid(): Boolean {
    throw TransactionException("No signature found")
}

抛出错误的保存方法

java.lang.reflect.InvocationTargetException

如果我将函数 name 更改为简单的 fun valid(),那么保存就可以了。

我只是好奇为什么函数的名称很重要?我也尝试将其更改为 fun isARadioactiveSpider() 之类的内容,但您会遇到同样的错误。

【问题讨论】:

    标签: android kotlin google-cloud-firestore


    【解决方案1】:

    firebase 类 CustomClassMapper 有一个方法:

    private static boolean shouldIncludeGetter(Method method) {
        if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) {
            return false;
        } else if (method.getDeclaringClass().equals(Object.class)) {
            return false;
        } else if (!Modifier.isPublic(method.getModifiers())) {
            return false;
        } else if (Modifier.isStatic(method.getModifiers())) {
            return false;
        } else if (method.getReturnType().equals(Void.TYPE)) {
            return false;
        } else if (method.getParameterTypes().length != 0) {
            return false;
        } else {
            return !method.isAnnotationPresent(Exclude.class);
        }
    }
    

    所以反射被用来序列化看起来像 getter 的方法。稍后将使用反射调用这些方法。而且这个调用抛出了一些异常,隐藏在InvocationTargetException

    所以,为了避免InvocationTargetException,只需检查方法不会抛出异常,因为它们是在序列化过程中调用的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-06
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多