gpt4 book ai didi

java - 序列化 - 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:59:06 26 4
gpt4 key购买 nike

我用类似 How to serialize an object into a string 的方法创建类并且它每次都说错误“java.lang.ClassCastException:java.lang.String cannot be cast to Myclass”

我的代码:1)

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.xml.bind.DatatypeConverter;

public class Serialization {

public static Object fromString(String s) throws IOException,
ClassNotFoundException {
byte[] data = DatatypeConverter.parseBase64Binary(s);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
data));
Object o = ois.readObject();
ois.close();
return o;
}

public static String toString(Serializable o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(o);
oos.close();
return DatatypeConverter.printBase64Binary(baos.toByteArray());
}
}

2) - 调用

MyClass hl = (MyClass) Serialization.fromString(items
.getString("data"));
hl.load(); // this is my method from class

3) MyClass - 全息图

public class Hologram implements Serializable {

/**
*
*/
private static final long serialVersionUID = 1L;

private Location loc;
private String name;
private String displayname;
public ArmorStand stand;

public Hologram(String name, String displayname, Location loc) {
this.loc = loc;
this.name = name;
this.displayname = displayname;

ArmorStand as = (ArmorStand) loc.getWorld().spawnEntity(loc,
EntityType.ARMOR_STAND);

as.setGravity(false);
as.setCanPickupItems(false);
as.setCustomName(displayname);
as.setCustomNameVisible(true);
as.setVisible(false);

this.stand = as;

HologramManager.holograms.put(name, this);

}

public void move(Location loc) {
this.loc = loc;

stand.teleport(loc);
}

public Location getLocation() {
return this.loc;
}

public void remove() {
stand.remove();
HologramManager.holograms.remove(name);
}

public void removeHologram() {
HologramManager.remove(name);
}

public void changeName(String name) {
HologramManager.holograms.remove(this.name);
this.name = name;
HologramManager.holograms.put(name, this);
}

public void changeDisplayName(String displayName) {
this.displayname = displayName;
stand.setCustomName(displayname);
stand.setCustomNameVisible(true);
}

public void load() {
//todo
}

}

最佳答案

根据链接的答案,问题很可能出在您没有向我们展示的代码中。当你序列化你的 MyClass 对象时,你可能正在做这样的事情:

MyClass hl;
String base64String = Serialization.toString(hl.toString());

但是你应该这样调用它:

MyClass hl;
String base64String = Serialization.toString(hl);

如果您将 String 传递给序列化函数,您将在调用 Serialization.fromString() 时返回一个 String。您想要取回一个可以转换为 MyClass 实例的对象,因此将其中一个传递给 Serialization.toString()

关于java - 序列化 - 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com