use Mix-In Annotations to reuse, decouple

本文介绍Jackson库中的Mix-in Annotations特性,该特性允许为第三方或遗留类注入序列化配置,无需修改原有类。通过示例展示了如何使用Mix-in Annotations解决序列化问题,并探讨了其在减少代码耦合方面的优势。

After reviewing the "number #1 user favorite feature" of upcoming Jackson 1.2 release, let's check out the Author's cut. As cool as ability to use any constructor or factory method a POJO has, my favorite feature is this little feature called Mix-in Annotations.

1. What are Mix-in Annotations?

Mix-in annotations are annotations defined in a mix-in class (or interface), that are to be used to augment annotations of a target class (or interface). Augmenting means that annotations of the mix-in class are used as if they were directly included in target class. Another way to explain this is to think of "mixing in annotations" to mean "injecting annotations from mix-in class to a target class".

Simple enough? There are obviously many smaller details (which will be explained later on), but for now this definition should suffice.

2. Example use case

Definition itself only describes what the feature is and does, but not why it would be useful. So let's consider an example use case.

Let's say you are using a third-party (or legacy) library that has a class called Point, defined as:

  public final class Point {
    final private int x, y;
    public Point(int x, int y) {
      this.x = x;
      this.y = y;
    }
    int x() { return x; }
    int y() { return y; }
    int getArea() { return x * y; }
  }

Point class is used extensively; including being exchanged between services. This means it needs to be serialized and deserialized.

Now Point is a perfectly ok POJO (and even somewhat typical one), but not one easily usable with data binding frameworks, including Jackson 1.1. Problems are:

  • Bean naming convention is not used, so that properties "x" and "y" are not serializable using getter methods; nor are fields public for automatic detection
  • Method "getArea" implies a bean property (and would be auto-detected), but we do NOT want to serialize property "area", since it is just a derived value and not an actual property
  • No default constructor is defined, but a 2-argument "initializing" constructor (not a problem per se with 1.2, any more); and that constructor is not marked as something we can use

So how would we serialize such a POJO?

Two main approaches would be adding annotations to guide the process; or writing a custom serializer.

In this case, we can not modify Point class definition itself; and ideally do not want to write custom serializers and deserializers, unless we absolutely have to.

3. Solution using Mix-in Annotations

So here is how you could use mix-in annotations to make Point (JSON) serializable: first, define a mix-in annotation interface (class would do as well):

  interface MixIn {
    @JsonProperty("x") int x();
    @JsonProperty("y") int y();
    @JsonIgnore int getArea();
  }

and then configure ObjectMapper to use that as a "mix-in" for Point like so:

  ObjectMapper mapper = new ObjectMapper();
  mapper.getSerializationConfig().addMixInAnnotations(Point.class, MixIn.class);

And voila! After doing this, Points would be serialized as containing integer properties "x" and "y"; not "area" as would happen by default.

Before considering the other part (deserialization), here are some notes on using Mix-in Annotations:

  • All annotation sets that Jackson recognizes (core annotationsJAXB extensions) can be mixed in
  • All kinds of annotations (member method, static method, field, constructor annotations) can be mixed in
  • Only method (and field) name and signature are used for matching annotations: access definitions (private etc) and method implementations are ignored. (hint: if you can, it oftenmakes sense to define mix-in class as an [abstract?] sub-class of target class, and use @Override JDK annotation to ensure method name and signature match!)
  • Mix-ins work as expected within inheritance hierarchy: it is feasible (and useful) to attach mix-in annotations to super-classes -- if so, mix-in annotations can further be overridden by annotations sub-classes (of target) provide.

4. Works for deserialization, too (or: "Better with BYOC")

So far so good? So here's another mix-in to tackle deserialization part -- the need to indicate constructor to use, and its parameter binding.

  abstract class DeserMixIn { // must be class to define constructors!
    DeserMixIn(@JsonProperty("x") int x, @JsonProperty("y") int y) { }
  }

and then just register this mix-in usingObjectMapper.getDeserializationConfig().addMixInAnnotations().
Note, too, that you could just create a single mix-in class to contain all annotations; they are here only separated for clarity.

It is also worth re-iterating that the ability to annotate "Creators" (constructors as well static factory methods) is the "other cool new feature" of Jackson 1.2.

So we can get Points out of JSON, so to speak.

5. So what IS the Point?

So the obvious first main benefit of this feature is that it makes it easier to work with legacy code; especially one you can not (or do not want to) modify by adding annotations. It is often good idea to let the sleeping code lie, unless you plan to do some significant refactoring. If it ain't broke, don't fix it.

But beyond this, it is also possible that perhaps you would ideally not add "special-purpose" (or perhaps, any at all) annotations to your POJOs. Arguably these annotations create a depedency to Jackson annotation classes, which should usually just be implementation details (assuming the main use for classes is not to serialize to JSON but do something else, aka "business logic"), and as such lead to unnecessary coupling of code.

So if you prefer to leave serialization-oriented annotations out of your biz-logic and data access/transfer classes, you could consider instead using Mix-in Annotations as the mechanism to associate necessary configuration information without introducing "wrong kind of" coupling. In a way, Mix-in Annotations can be viewed kind of Aspect-Oriented (or maybe Inversion-of-Control) feature. They allow injecting runtime serialization/deserialization configuration information, using dynamic (but non-intrusive: no code is modified!) mechanism.

7. Keep on Innovating!

One more thing: I think that this feature is one of the first features that is truly innovative with Jackson. There are many things that are improved, and perhaps even clever. But Mix-in Annotations is something I haven't seen in other libraries yet. Given this, I am curious to learn how users feel about it -- leave a comment here, or send email: let me know how you really feel!

The idea is of course to continue innovating. 1.3 is planned to contain similarly innovative features to make it possible, for example, to bind objects from regular Maps (and vice versa). Why? Well, wouldn't it be nice to create POJOs out of those nice little Java properties files? I think so too!

内容概要:本文介绍了基于贝叶斯优化的CNN-LSTM混合神经网络在时间序列预测中的应用,并提供了完整的Matlab代码实现。该模型结合了卷积神经网络(CNN)在特征提取方面的优势与长短期记忆网络(LSTM)在处理时序依赖问题上的强大能力,形成一种高效的混合预测架构。通过贝叶斯优化算法自动调参,提升了模型的预测精度与泛化能力,适用于风电、光伏、负荷、交通流等多种复杂非线性系统的预测任务。文中还展示了模型训练流程、参数优化机制及实际预测效果分析,突出其在科研与工程应用中的实用性。; 适合人群:具备一定机器学习基基于贝叶斯优化CNN-LSTM混合神经网络预测(Matlab代码实现)础和Matlab编程经验的高校研究生、科研人员及从事预测建模的工程技术人员,尤其适合关注深度学习与智能优化算法结合应用的研究者。; 使用场景及目标:①解决各类时间序列预测问题,如能源出力预测、电力负荷预测、环境数据预测等;②学习如何将CNN-LSTM模型与贝叶斯优化相结合,提升模型性能;③掌握Matlab环境下深度学习模型搭建与超参数自动优化的技术路线。; 阅读建议:建议读者结合提供的Matlab代码进行实践操作,重点关注贝叶斯优化模块与混合神经网络结构的设计逻辑,通过调整数据集和参数加深对模型工作机制的理解,同时可将其框架迁移至其他预测场景中验证效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值