alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

父类的方法有@JSONField,子类重写发现注解被丢失 #3129

Open JoeyBling opened 4 years ago

JoeyBling commented 4 years ago

Demo代码:

package com.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

import java.io.Serializable;

/**
 * 父类的方法有@JSONField,子类重写发现注解被丢失
 *
 * @author Created by 思伟 on 2020/4/20
 */
public class TestFastJson {

    public static void main(String[] args) {
        System.out.println(JSON.toJSONString(new B()));
    }

    interface Entity extends Serializable {
        String getModule();
    }

    static class A implements Entity {

        @Override
        @JSONField(serialize = false)
        public String getModule() {
            return "AAA";
        }
    }

    static class B extends A {

        @Override
        public String getModule() {
            return this.getClass().getSimpleName();
        }
    }

}

输出结果:

{"module":"B"}

Korov commented 4 years ago

重写父类方法注解是不会被继承的,不仅仅是JSONField注解,其他注解也不会被继承

JoeyBling commented 4 years ago

看了下源码,应该是TypeUtils.getAnnotation 无法获取继承的注解。 顺带看了下Spring是如何获取继承的注解的。通过AnnotationUtils.findAnnotation可以正常获取。

贴下代码

// 获取父类注解
Class<?> bClass = B.class;
for (Method method : bClass.getDeclaredMethods()) {
// FastJson内置获取注解无法获取
JSONField annotation = TypeUtils.getAnnotation(method, JSONField.class);
// false
System.out.println(annotation != null);
annotation = AnnotationUtils.getAnnotation(method, JSONField.class);
// false
System.out.println(annotation != null);
annotation = AnnotationUtils.findAnnotation(method, JSONField.class);
// True
System.out.println(annotation != null);
annotation = AnnotatedElementUtils.findMergedAnnotation(method, JSONField.class);
// True
System.out.println(annotation != null);
}

不知道是FastJson团队设计如此,还是其他的问题... 还是比较希望能把这问题再优化下,或者通过可配置方法进行开启获取父类注解

czjxy881 commented 3 years ago

+1