使用Java中的注释跟踪脏属性?

时间:2014-12-08 01:10:13

标签: java enums annotations

我有一个问题,我正在努力解决。我有一些模型对象,我想跟踪它们的属性是否有变化。由于这些模型的使用模式,我希望跟踪是自包含的,以便以下工作:

Student student = new Student();
student.setName = "name";
List<StudentProperties> changedProperties = student.getChangedProperties();
//changedProperties = { StudentProperties.name }

我的第一直觉是创建一个内部hashmap和属性枚举,然后通过修改setter来更新hashmap来跟踪更改。我不是粉丝,因为它不是通用的,因此我不能对我的所有模型使用一个实现。

是否有一个干净的解决方案:

@TrackChanges
public class Student implements Trackable {
    @Track
    private String name;

    public List<StudentProperties> getChangedProperties() {
        //somehow return changed properties
    }
}

通过注释创建属性枚举,以及包含getChangedProperties()可返回的属性的地图。

我愿意使用可观察的模式,但是我不确定它如何与模型的客户端一起工作(我是否必须强制它们在使用我的模型之前也遵循观察者模式?声音侵扰性,因此我不赞成它。)

由于

2 个答案:

答案 0 :(得分:0)

根据Aspect(文章的第二部分)和PropertyChangeSupport查看this solution。它干净而通用

您可以轻松地对其进行调整,以限制对@Track

注释的属性的跟踪

http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop

答案 1 :(得分:0)

我创建了一个名为AValueObject的基类,它包含一个处理此问题的DirtyTracker属性:https://github.com/subes/invesdwin-util#dirtytracker

我还创建了一个AspectJ方面,为您处理PropertyChangeSupport事件:https://github.com/subes/invesdwin-aspects#propertychangesupportedaspect