IllegalArgumentException:无法序列化类(即使它实现了Serializable)

时间:2016-09-08 17:32:30

标签: java mongodb serialization lombok nosql

我成功建立了一个MongoDB数据库,我的Java程序正好连接到它。但是,当我尝试保存此类的实例时,出现错误:

@Data
public class NormalUser extends User implements Serializable {

    private static final long serialVersionUID = 1324235L;

    public NormalUser(final String name, final String surname, final String address,
                      final String dni, final Gender gender, final String bankAccount) {
        super(name, surname, address, dni, gender, bankAccount, Role.NORMAL_USER, false);
    }
}

(请注意我使用的是Lombok @Data注释,并且该类扩展了另一个使用相同注释的类,并且只有构造函数和属性。)

从我的观点来看,我得到的错误是奇怪的,只要它说类不能被序列化,即使它实现了Serializable

Exception in thread "main" java.lang.IllegalArgumentException: can't serialize class entities.users.NormalUser
    at org.bson.BasicBSONEncoder._putObjectField(BasicBSONEncoder.java:270)
    at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:174)
    at org.bson.BasicBSONEncoder.putObject(BasicBSONEncoder.java:120)
    at com.mongodb.DefaultDBEncoder.writeObject(DefaultDBEncoder.java:27)
    at com.mongodb.OutMessage.putObject(OutMessage.java:289)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:261)
    at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
    at com.mongodb.DBCollection.insert(DBCollection.java:75)
    at com.mongodb.DBCollection.insert(DBCollection.java:59)
    at com.mongodb.DBCollection.insert(DBCollection.java:104)
    at repositories.UsersRepository.createUser(UsersRepository.java:35)
    at repositories.UsersRepository.main(UsersRepository.java:68)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

更新

这是超级课程:

@Data
public abstract class User implements Serializable {

    static final long serialVersionUID = 12314362564783L;

    private String surname;
    private String address;
    private String dni;
    private Gender gender;
    private String bankAccount;
    private Role role;
    private boolean admin;
    private String name;

    public User(final String name, final String surname, final String address,
                final String dni, final Gender gender, final String bankAccount,
                final Role role, final boolean admin) {
        this.name = name;
        this.surname = surname;
        this.address = address;
        this.dni = dni;
        this.gender = gender;
        this.bankAccount = bankAccount;
        this.role = role;
        this.admin = admin;
    }
}

更新#2 这足以序列化枚举 Gender吗?

public enum Gender implements Serializable {

    MALE, FEMALE;
}

0 个答案:

没有答案