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

q9rjltbz  于 2023-02-04  发布在  其他
关注(0)|答案(3)|浏览(277)

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"}

9w11ddsr

9w11ddsr1#

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

cnjp1d6j

cnjp1d6j2#

看了下源码,应该是 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团队设计如此,还是其他的问题...
还是比较希望能把这问题再优化下,或者通过可配置方法进行开启获取父类注解

相关问题