英文:
Getting notified of deserialization of a subclass within that class
问题
我正在尝试为特定类型的对象实现日志记录系统。
我将它们存储在不同类的静态方法内的WeakHashMap
中。这样,我可以监视它们的更改,而不影响它们的构造/析构时间。但唯一的问题是,这些对象是可序列化的,并且会频繁地进行序列化/反序列化操作。
为了提供更多细节,所涉及的类是框架内定义的类的子类型。子类在该框架内进行序列化/反序列化,因此我无法从超类中更改这种行为(因为该代码位于框架中)。由于某种原因,在子类上不需要实现反序列化,框架会自动处理。
问题在于,虽然我可以像这样记录对象:
public abstract class Thing implements Serializable {
// 这个类的定义和声明位于一个框架内部
}
public class ClassIWantToLog extends Thing {
public ClassIWantToLog(/*参数*/) {
super(/*参数*/
/*和此相关的内容*/
StaticToolsClass.logWithWeakReference(this);
}
}
但如果该对象被序列化然后再次反序列化,我就会丢失引用,因此它会从我的WeakHashMap
中删除,而当它被重新创建时,此构造函数不会被调用,因此无法重新将其添加到WeakHashMap
中。
目标是在ClassIWantToLog
内部自动调用的某个方法,以便在对象被反序列化时传递该新对象给StaticToolsClass
。
如果有必要的话,我愿意使用反射,并且如果可能的话,希望重写所述方法不会增加太多代码(例如:我不想额外实现自定义反序列化)。
英文:
I am trying to implement a logging system for objects of a specific type.
I am storing them in a WeakHashMap
inside of a static method of a different class. This way I can monitor their changes without influencing when they are constructed/deconstructed. The one issue with this is that these objects are serializable and will FREQUENTLY be serialized/deserialized.
To add some more detail the class in question is a subtype of a class that is defined inside of a framework. The subclass is serialized/deserialized inside of this framework so I have no way of changing this behavior from the superclass (because that code is in the framework). For some reason one does not have to implement deserialization on the sub class and it is handled automatically by the framework.
The problem is while I can log object like so
public abstract class Thing implements Serializable {
// This classes definition and declaration lives inside of a framework
}
public class ClassIWantToLog extends Thing {
public ClassIWantToLog(/*ARGS*/) {
super(/*ARGS*/
/*Things with this*/
StaticToolsClass.logWithWeakReference(this);
}
}
If that object is ever serialized than deserialized I loose the reference so it is removed from my WeakHashMap
and when it is recreated this constructor is not called so I cant re-add it to my WeakHashMap
.
The goal would be to somehow override a method that will automatically be called inside of ClassIWantToLog
when it is deserialized so I can pass that new object to StaticToolsClass
.
I am willing to use reflection if that is necessary and if at all possible hopefully overriding said method would not add too much code (ex: I don't want to have to implement custom deserialization as well).
专注分享java语言的经验与见解,让所有开发者获益!
评论