使用 AspectJ 编织 toString() 实现 [英] Weaving in toString() implementation with AspectJ

查看:26
本文介绍了使用 AspectJ 编织 toString() 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试为大量 DTO 使用默认的 toString() 方法编织,仅使用编译时编织.目标是使用 Jackson 库返回 JSON 表示.

Trying to weave in a default toString() method for a large number of DTOs, using compile-time weaving only. The goal is to return a JSON representation using the Jackson library.

按照这篇文章中的建议,把它变成了annotation-style aspect配置,最后得到以下代码:

Followed the suggestions in this article, turned it into annotation-style aspect config, and ended up with the following code:

public @Aspect class JsonToStringAspect {
    private interface JsonToString {
        public String toString();
    }

    public static class JsonToStringImpl implements JsonToString {
        public String toString() {
            return SingletonJsonEncoder.toJsonString(this);
        }
    }

    @SuppressWarnings("unused")
    @DeclareParents(value = "com.mycompany.dto..*", defaultImpl = JsonToStringImpl.class)
    private JsonToString implementedInterface;
}

在生成的类上运行 javap 表明它们实现了 JsonToString 接口,但在任何地方都没有 toString() 方法的迹象.

Running javap on the resulting classes shows that they implement the JsonToString interface, but there's no sign of the toString() method anywhere.

如果我将方法名称更改为不与 Object.toString() 冲突的名称(例如 toString2()),则该方法确实添加了.

If I change the method name to something that doesn't collide with Object.toString() (e.g. toString2()), the method is truly added.

关于如何克服这个问题的任何线索?也许一个 @Around 建议关于拦截 java.lang.Object.toString() 执行的切入点,仅适用于包 com.mycompany.dto 下的子类?或者强制混合发生的方法?

Any clues on how to overcome this? Maybe an @Around advice on a pointcut that intercepts the execution of java.lang.Object.toString(), only for children classes below package com.mycompany.dto? Or a way to force the mixin to happen?

推荐答案

我尝试了你的场景并且可以复制行为,我也尝试了 @DeclareMixin 而不是 @DeclareParent 的组合代码>,也无法让它工作.不过对我有用的是以这种方式使用本机aspectj:

I tried your scenario and could replicate the behavior, I also tried combinations of @DeclareMixin instead of @DeclareParent and could not get that to work either. What worked for me though is to use native aspectj this way:

public aspect JsonToStringAspect {
    private interface JsonToString {}
    declare parents: com.mycompany.dto.* implements JsonToString;

    public String JsonToString.toString() {
        return "Overridden String through JsonToStringAspect";
    }
}

我猜这在使用 @AspectJ 时可能不可行,并且可能只能通过原生方面实现.

I am guessing that this may not be feasible using @AspectJ and may be possible only through native aspects.

这篇关于使用 AspectJ 编织 toString() 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆