我正在尝试使用 Groovy 将byte []转换为Object。我的实际Groovy类由字节数组表示,它实现了Serializable接口,并存储在一个单独的Groovy类文件中。但是,在尝试调用ClassNotFoundException
函数时,我总是得到此类的toObject
。我的代码是用Java编写的,在使用Java时可以工作,但在使用Groovy时则不行。
private static byte[] toByteArray(Object obj) {
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
}
return bytes;
}
private static Object toObject(byte[] bytes) {
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
} catch (Exception ex) {
ex.printStackTrace(); // ClassNotFoundException
}
return obj;
}
这样做的最佳方式是什么?
编辑:在此上下文中将出现ClassNotFoundException的类是这样的:
public class MyItem implements Serializable {
/**
*
*/
private static final long serialVersionUID = -615551050422222952L;
public String text
MyItem() {
this.text = ""
}
}
然后测试整个事情:
void test() {
MyItem item1 = new MyItem ()
item1.text = "bla"
byte[] bytes = toByteArray(item1) // works
Object o = toObject(bytes) // ClassNotFoundException: MyItem
MyItem item2 = (MyItem) o
System.out.print(item.text + " <--> " + item2.text)
}
答案 0 :(得分:1)
我的猜测(这也是@JustinPiper建议的)是你在引用它之前没有编译你的groovy类。您必须使用groovyc编译groovy类,并确保已编译的类文件放在类路径上(可能与java测试类位于同一文件中)。