简体   繁体   English

将对象强制转换为其父类以避免在Java中使用其属性

[英]Casting an Object to its father class for avoiding its attributes in Java

I have class SuperYo extending class Persona, like this: 我有SuperYo类扩展了Persona类,如下所示:

public class SuperYo extends Persona {

   private NotSerializableObj obj1
   private NotSerializableObj obj2
   private NotSerializableObj obj3

}

public class Persona {

   private SerializableObj sObj1
   private SerializableObj sObj2
   private SerializableObj sObj3

}

The thing is, that I add to a LinkedList an Instance of Persona from SuperYo: 问题是,我将SuperYo中的Persona实例添加到LinkedList中:

LinkedList<Persona> list = new LinkedList<Persona>();
list.add((Persona) superYo);

It adds it as a SuperYo Object! 它将其添加为SuperYo对象! With all the NonSerializableObjs on it... and thus, cant be sent from a Socket :(. 上面有所有的NonSerializableObjs ...,因此不能从Socket :(。发送。

So, the question is... is there any way of "downcasting" an object to its father class, so its attributtes are non present? 因此,问题是...是否有任何方法可以将对象“下放”到其父类,因此其属性不存在?

Thanks! 谢谢!

Casting is a matter of polymorphism. 铸造是多态性的问题。 When you cast an object of type1 to type2, the instance won't change, but you just look at the instance from a new perspective! 当您将类型1的对象转换为类型2时,实例不会更改,而只是从新的角度看实例!

If you want to send the child class over the network, you can make the SuperYo members as transient, and fill them on instantiation. 如果要通过网络发送子类,则可以使SuperYo成员成为瞬态成员,并在实例化时填充它们。 Or you can add writeObject() and readObject() methods to your child class. 或者,您可以将writeObject()和readObject()方法添加到子类中。

Implement readObject and writeObject in SuperYo as below: SuperYo实现readObjectwriteObject ,如下所示:

 private void writeObject(ObjectOutputStream outStream) throws IOException {
    //write attributes from PersonYo only
    outStream.defaultWriteObject();
    outStream.writeObject(sObj1);
    outStream.writeObject(sObj2);
    outStream.writeObject(sObj2);
 }

private void readObject(ObjectInputStream inStream) throws IOException,
                                                          ClassNotFoundException {
    //read attributes from PersonYo only
    inStream.defaultReadObject();
    sObj1= (SerializableObj)inStream.readObject();
    sObj2= (SerializableObj)inStream.readObject();
    sObj3= (SerializableObj)inStream.readObject();
}

Once you do this, there will be no need of down-casting. 完成此操作后,将无需进行向下转换。 Also you may have better control on other non-serializable attributes in the object. 同样,您可以更好地控制对象中的其他不可序列化的属性。

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

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