简体   繁体   English

在Java中,在处理序列化和来自另一个可实例化类的引用时,引用用户定义的类如何工作?

[英]In java, how does referencing a user defined class work when dealing with serialization and reference from another instantiable class?

I have a class which is serializable, say class " WriteMe ". 我有一个可序列化的类,比如说“ WriteMe ”。 This class needs another class to update one of its members. 此类需要另一个类来更新其成员之一。 Said class is relatively large, since WriteMe is just a wrapper class mostly. 该类相对较大,因为WriteMe主要只是包装类。 We will call the large class " MegaClass ". 我们将大型类称为“ MegaClass ”。 Therefore we have something like this: 因此,我们有这样的事情:

public class WriteMe implements Serializable
{
    private ArrayList<String> list;
    private String name;

    public WriteMe(String s)
    {
        name = s;
    }

    public void update(MegaClass m)
    {
        list = m.getList(name);
    }
}

The hopeful point in doing this is that I don't want to store MegaClass as a class variable like the ArrayList and String are. 这样做的希望在于,我不想将MegaClass作为ArrayListString这样的类变量存储。 I'm hoping by passing it in to a method and only using it there where it's needed , I will reduce the amount of memory used when creating a WriteMe , and also reduce the file-size of a WriteMe object, if I were to pass it to an ObjectOutputStream or similar (so that it can be written to file). 我通过把它传递给一个方法希望, 只有使用它有它需要的地方,我会减少内存创建时使用的量WriteMe同时也减少的文件大小WriteMe对象,如果我是通过它到ObjectOutputStream或类似对象(以便可以将其写入文件)。

Does " Megaclass m " just store a pointer to the instantiation of that object? Megaclass m ”是否仅存储指向该对象实例化的指针? If so, I would imagine that it doesn't matter if I make it a class variable or not, since an address is just a few bytes or so. 如果是这样,我可以想象是否将其设置为类变量都没有关系,因为地址只有几个字节左右。 Is there any advantage to using the object passed into the method only, as shown above? 如上所示,仅使用传递给方法的对象有什么好处? The other way is to pass it into the constructor and assign as a class variable. 另一种方法是将其传递到构造函数中并分配为类变量。 Is either way advantageous? 任一种方法都有利吗?

As Mark W. suggests, the best thing to do is to separate the use of "MegaClass" and "WriteMe", so that all that is required by WriteMe is the data. 正如Mark W.建议的那样,最好的办法是将“ MegaClass”和“ WriteMe”的使用分开,以便WriteMe所需的全部是数据。

public void update(ArrayList<String> newList)
{
    list = newList;
}

In this manner, a super class which has a reference to both classes may inquire from MegaClass "What is the correct data?", and pass this information to WriteMe! 以这种方式,可以同时向MegaClass查询“引用正确的数据是什么”的超类,并将其传递给WriteMe! A bonus of this is that no transient data is needed, nor ANY reference to the MegaClass at all! 这样做的好处是,不需要瞬态数据,也根本不需要任何对MegaClass的引用!

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM