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

查看:116
本文介绍了用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.

按照本文中的建议,将其转变为注释样式配置,并以以下代码结束:

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.

关于如何克服这一点的任何线索?也许仅针对包com.mycompany.dto以下子类的切入点上的@Around建议会拦截java.lang.Object.toString()的执行?还是强迫混合发生的方法?

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天全站免登陆