You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Java迁移到Kotlin后,Data Binding无法调用单例类方法的问题

Fixing Data Binding Call to Kotlin Singleton Method

Got it, let's break down why your Data Binding setup can't locate the hideNumber method from your StringValidator singleton, and how to fix it.

The Root Cause

Kotlin's object keyword creates a singleton, but by default, its member methods aren't exposed as static methods to Java code. Since Data Binding is built on Java under the hood, calling StringValidator.hideNumber(...) directly expects a static method—which doesn't exist unless you explicitly mark it as such.


Solution 1: Mark the Method with @JvmStatic

The simplest fix is to add the @JvmStatic annotation to your hideNumber method. This tells the Kotlin compiler to generate a static version of the method that Java (and Data Binding) can recognize:

object StringValidator {
    // ... other methods/properties

    @JvmStatic
    fun hideNumber(number: String): String {
        return "****" + number.substring(number.length - 4)
    }
}

Now your original Data Binding call will work as expected:

<data>
    <import type="com.your.package.StringValidator" />
</data>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{StringValidator.hideNumber(account.number)}" />

(Don't forget to replace com.your.package with the actual package path of StringValidator.)


Solution 2: Use a Singleton Instance Variable in Data Binding

If you prefer not to use @JvmStatic, you can create a variable in your layout that references the singleton instance, then call the method on that variable:

  1. Update your layout's <data> section:
<data>
    <import type="com.your.package.StringValidator" />
    <variable
        name="validator"
        type="StringValidator" />
</data>
  1. Assign the singleton instance in your Activity/Fragment:
// In your onCreate (Activity) or onViewCreated (Fragment)
binding.validator = StringValidator
  1. Call the method via the variable:
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@{validator.hideNumber(account.number)}" />

Bonus: Handle Null Safety

To avoid crashes if account.number is null, add a null check in your Data Binding expression:

android:text="@{account.number != null ? StringValidator.hideNumber(account.number) : ``}"

内容的提问来源于stack exchange,提问作者Sigmund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:05:17