转换为Object的Java LinkedHashMap是否序列化为另一个类?

hgc7kmma  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(132)

我试图将LinkedHashMap序列化为ObjectOutputStream,但遇到了一些奇怪的情况。ObjectOutputStream,将LinkedHashMap转换为Object,但它不是LinkedHashMap,它被写为我的类SQLRow?!

Host.instance.getLogger().info("Sending back player data...");
final LinkedHashMap<String, NetworkedSQLObject> hm = MirageSQLTables.players.getByPrimaryKey(rest.readUTF()).getAsSocketEligibleMap();
Host.instance.getLogger().info("Linked Hash Map class name: " + hm.getClass().getName());
c.sendMessage(new SQLObjectResponsePacket(pID, (Object)hm));

注意:函数getByPrimaryKey()是一个自定义SQL函数,它返回我的自定义类SQLRow
上面代码的输出:

14:37:03 [INFO] [Host] Sending back player data...
14:37:03 [INFO] [Host] Getting col: id
14:37:03 [INFO] [Host] Getting col: name
14:37:03 [INFO] [Host] Getting col: date_joined
14:37:03 [INFO] [Host] Getting col: rank
14:37:03 [INFO] [Host] Getting col: moderator
14:37:03 [INFO] [Host] adding NetworkedSQLObject: id:TEXT -> 2
14:37:03 [INFO] [Host] adding NetworkedSQLObject: name:TEXT -> KrispWasntTaken
14:37:03 [INFO] [Host] adding NetworkedSQLObject: date_joined:TIMESTAMP -> 2023-06-14 18:19:15.0
14:37:03 [INFO] [Host] adding NetworkedSQLObject: rank:INT -> 0
14:37:03 [INFO] [Host] adding NetworkedSQLObject: moderator:BIT -> true
14:37:03 [INFO] [Host] Linked Hash Map class name: mirage.database.sql.SQLRow$1 <---- HERE!

它在NetworkedSQLObject构造函数中说明了同样的事情。函数getAsSocketEligibleMap()在SQLRow类内部,但我真的很困惑,因为它与类没有关系,并返回一个新的LinkedHashMap,而不是SQLRow的示例...
getAsSocketEligibleMap()代码:

public LinkedHashMap<String, NetworkedSQLObject> getAsSocketEligibleMap(){
        return new LinkedHashMap<>(){{
            Set<Map.Entry<String, SQLObject>> es = data.entrySet();

            Iterator<Map.Entry<String, SQLObject>> i = es.iterator();

            while(i.hasNext()){
                Map.Entry<String, SQLObject> entry = i.next();
                Host.instance.getLogger().info("adding NetworkedSQLObject: " + entry.getKey() + ':' + entry.getValue().getType() + " -> " + entry.getValue().getValue());
                put(entry.getKey(), new NetworkedSQLObject(entry.getValue()));
            }
        }};
    }

任何帮助都很感激…

rbl8hiat

rbl8hiat1#

您已经在类中使用了双括号初始化模式,这通常不是理想的模式(双{{}})。它所做的是有效地定义一个新的内部类。因此,您返回的不是一个实际的LinkedHashMap,而是一个从LinkedHashMap扩展而来的匿名内部类。因为它是一个内部类,所以它也保留了对 * 外部 * 类的引用,在本例中是SQLRow类。只需删除双括号初始化模式就可以解决您的问题。(这是应该避免该模式的众多原因之一)。

相关问题