简体   繁体   English

Java 序列化库,不需要无参数构造函数和 Serializable 的实现

[英]Java serialization library without need of no-arg constructors and implementation of Serializable

java-world 中是否有任何方法可以在不需要无参数构造函数和 Serializable 实现的情况下进行序列化?

JBoss Serialization is a drop-in replacement for standard java serialization, which does not require you to implement java.io.Serializable . JBoss Serialization是标准 java 序列化的直接替代品,它不需要您实现java.io.Serializable Other than that (and the fact that it's much faster), it's the same as the standard serialization mechanism (it even uses the same ObjectInput and ObjectOutput interfaces.除此之外(以及它更快的事实),它与标准序列化机制相同(它甚至使用相同的ObjectInputObjectOutput接口。

PS It has no dependency on other JBoss stuff, it's just one of the JBoss low-level libraries broken out as a separate project. PS 它不依赖于其他 JBoss 的东西,它只是作为单独项目分解的 JBoss 低级库之一。

A horrific way to do it would be to build a parallel hierarchy of classes, each one standing in for one of the classes in the third-party hierarchy, each of which implements Externalizable, and writes itself by writing the appropriate fields from the third-party object.一种可怕的方法是构建一个并行的类层次结构,每个类都代表第三方层次结构中的一个类,每个类都实现了 Externalizable,并通过从第三方写入适当的字段来编写自己 -当事人对象。

I wouldn't, though.不过我不会。

See http://www.jguru.com/faq/view.jsp?EID=251942 explanation.参见http://www.jguru.com/faq/view.jsp?EID=251942解释。

The only requirement on the constructor for a class that implements Serializable is that the first non-serializable superclass in its inheritence hierarchy must have a no-argument constructor.对实现Serializable的类的构造函数的唯一要求是其继承层次结构中的第一个不可序列化的超类必须具有无参数构造函数。

  1. Serializeble without no-argument constructor as extends Object with with no-argument constructor没有无参数构造函数的可序列化作为具有无参数构造函数的扩展Object

     public class MySerializableClass implements Serializable { public MySerializableClass (...)... }
  2. Serializeble without no-argument constructor as extends MyFirstClass with with no-argument constructor Serializeble 没有无参数构造函数作为扩展MyFirstClass与无参数构造函数

     public class MyFirstClass { } public class MySecondClass extends MyFirstClass implements Serializable { public MySecondClass (...)... }
  3. NOT serializeble as MyFirstClass is not implement Serializable AND have not default constructor.不可序列化,因为MyFirstClass没有实现Serializable并且没有默认构造函数。

     public class MyFirstClass { public MyFirstClass (...)... } public class MySecondClass extends MyFirstClass implements Serializable { public MySecondClass (...)... }

I believe in some cases you can force serialization despite the Type's declarations.我相信在某些情况下,尽管 Type 有声明,但您可以强制序列化。 However there is inherent risk as the class may have fields that are not serializable, which will cause runtime exceptions.然而,存在固有风险,因为该类可能具有不可序列化的字段,这将导致运行时异常。

I'm curious though as you get no-arg default constructors for free, unless you have written custom constructors.我很好奇,因为您可以免费获得无参数的默认构造函数,除非您编写了自定义构造函数。 Also implmenting Serializable takes 30 seconds of find/replace.实现 Serializable 也需要 30 秒的查找/替换。

Is there a reason you are trying to avoid these?你有什么理由试图避免这些吗?

...and implementation of Serializable? ...和Serializable的实现?

Unfortunately not.不幸的是没有。 All Serializable objects must implement java.io.Serializable .所有 Serializable 对象都必须实现java.io.Serializable As for your first part of the question, you can use ObjectInputStream / ObjectOutputStream to serialize objects to byte array and vice versa.至于问题的第一部分,您可以使用ObjectInputStream / ObjectOutputStream将对象序列化为字节数组,反之亦然。

The following example shows how to:以下示例显示了如何:

public static byte[] toByteArray(Object object) throws IOException {
        if (!isSerializable(object)) {
            throw new IOException("Object '" + object.getClass().getName() + "' is not serializable.");
        }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(baos);
        oos.writeObject(object);
        oos.flush();
    } finally {
        if (oos != null) {
            try {
                oos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error("Closing of ObjectOutputStream failed.", e);
            }
        }
    }

    return baos.toByteArray();
}

public static Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
    Object object = null;
    ObjectInputStream ois = null; 

    try {
        ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        object = ois.readObject();
    } finally {
        if (ois != null) {
            try {
                ois.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                logger.error("Closing of ObjectInputStream failed.", e);
            }
        }
    }

    return object;
}

Eishay Smith has done a benchmarking of Java serializers which includes some information about each one , although it doesn't say whether they use no-arg constructors (and in many cases, they don't even work with arbitrary objects, so the question is moot). Eihay Smith对 Java 序列化程序进行了基准测试,其中包含有关每个序列化程序的一些信息,尽管它没有说明它们是否使用无参数构造函数(并且在许多情况下,它们甚至不使用任意对象,所以问题是没有实际意义)。 That might be worth a look.那可能值得一看。

And Databoard , it can serialize bean-style, record-style and immutable-style classes.Databoard 一样,它可以序列化 bean 风格、记录风格和不可变风格的类。 You can also write own class-external binding.您还可以编写自己的类外部绑定。

There are a range of alternatives as other people have said.正如其他人所说,有一系列替代方案。 If you want to stick with standard Java serialization with writeObject and readObject, you could write your own adapter class that inherits from a third party class, implement Serializable on your own class, and override writeObject and readObject, in other words, implement custom serialization for your class.如果您想坚持使用 writeObject 和 readObject 的标准 Java 序列化,您可以编写自己的从第三方类继承的适配器类,在您自己的类上实现 Serializable,并覆盖 writeObject 和 readObject,换句话说,实现自定义序列化你的班。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 Java 包装类没有无参数构造函数? - Why don't Java wrapper classes have no-arg constructors? Java子类的实参构造函数中的no-arg super()编译器调用 - Compiler calls to no-arg super() in argumented constructors of child classes in java 有效 Java。 可序列化生成器模式(如何添加公共无参数构造函数?) - Effective Java. Serializable Builder pattern (how to add public no-arg constructor?) 有多个好的构造函数,Room 会选择无参数的构造函数 - There are multiple good constructors and Room will pick the no-arg constructor 为什么无参数构造函数必须以无效状态实例化? - Why are no-arg constructors subject to being instantiated in an invalid state? 序列化Java:哪些类需要“实现Serializable”? - Serialization Java: which classes need to “implement Serializable”? 如何在泛型类中正确键入no-arg和withVar构造函数? - How to correctly type no-arg and withVar constructors in a generic class? 如果父级没有no-arg构造函数,则出现序列化问题 - Serialization issue if the parent does not have a no-arg constructor 是否有可能在java中使用反射创建没有arg构造函数的类的“空白”实例? - Is it possible in java to create 'blank' instance of class without no-arg constructor using reflection? Java:0个arg构造函数和构造函数的问题 - Java: Issues with 0 arg constructors and constructors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM