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

Realm生成代码报错:返回类型Integer与int不兼容问题咨询

Fixing Realm's Integer vs int Type Mismatch Error

Hey there, let's break down why you're hitting that "Integer与int不兼容" error when Realm generates code for your User model, and how to fix it.

The Root Cause

Looking at your code, you’ve annotated your int id field with @Id(IntegerIdHandler.class). The core issue here is that IntegerIdHandler is explicitly built to work with the Integer wrapper type, not the primitive int type. When Realm tries to generate its proxy classes for your model, it expects the field type to match what the handler is designed for—hence the type mismatch error.

Solutions to Resolve This

1. Switch the id Field to Integer (Simplest Fix)

The quickest way to fix this is to change your id field from the primitive int to the Integer wrapper type. This aligns perfectly with IntegerIdHandler's expected type:

@Data
@Type("user")
@Builder()
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"id", "email"}, callSuper = true)
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class)
public class User extends RealmObject {
    @PrimaryKey
    @Id(IntegerIdHandler.class)
    private Integer id; // Replace int with Integer here
    private String firstName;
    private String lastName;
    private String email;
    @Ignore
    private String password;
    private boolean isAdmin;
    private boolean isSuper;
    // Rest of your fields/methods
}

After making this change, clean your project and rebuild it—Realm will generate the correct proxy classes without any type conflicts.

2. Create a Custom IntIdHandler (If You Need Primitive int)

If your business logic requires sticking with the primitive int type for id, you can create a custom IdHandler that works with int (via auto-boxing to Integer):

public class IntIdHandler implements IdHandler<Integer> {
    @Override
    public Integer generateId() {
        // Implement your primary key generation logic here
        // Example: Return an auto-incrementing int value (boxed to Integer)
        return yourIntIdGenerationLogic();
    }

    @Override
    public Class<Integer> getIdType() {
        return Integer.class;
    }
}

Then update your User model to use this custom handler:

@PrimaryKey
@Id(IntIdHandler.class)
private int id;

Just make sure your generateId() method never returns null—since int can’t hold a null value, a null return here would trigger a NullPointerException during auto-unboxing.

3. Clean & Rebuild Your Project

No matter which solution you pick, always run a clean build after modifying your model class. This ensures Realm discards any old generated proxy classes and creates fresh ones that match your updated code.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:45:19