为什么JAXB生成的类具有受保护的成员?如何更改它? [英] Why do JAXB generated classes have protected members and how can I change this?

查看:105
本文介绍了为什么JAXB生成的类具有受保护的成员?如何更改它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上搜索JAXB生成的类有保护成员的原因(所有这些都是继承的)。

I have been searching the internet for a reason why JAXB generated classes have protected members (all of them, regardless of inheritance).

我希望这些成员是私人的。

I would like the members to be private instead.

我的搜索结果为空。

我有正常的xsd文件,使用Maven和JAXB转换为Java类。理想情况下,生成的成员应该是私有的,但我找不到实现此目的的方法。

I have normal xsd files which are converted into Java classes using Maven and JAXB. Ideally the generated members should be private but I cannot find a way to achieve this.

有没有办法修改这种默认行为?

Is there a way to modify this default behaviour?

推荐答案

好吧,我将回答我自己的问题。
创建一个插件是正确的方法。

Well, I am going to respond to my own question. Creating a plugin was the right way to go.

我编写了以下插件,它似乎有效。

I wrote the following plugin and it seems to work.

public class PrivateMemberPlugin
    extends Plugin
{

    @Override
    public String getOptionName()
    {
        return "Xpm";
    }

    @Override
    public String getUsage()
    {
        return "  -Xpm    : Change members visibility to private";
    }

    @Override
    public boolean run(Outline model, Options opt, ErrorHandler errorHandler)
        throws SAXException
    {
        for (ClassOutline co : model.getClasses())
        {

            JDefinedClass jdc = co.implClass;
            // avoid concurrent modification by copying the fields in a new list
            List<JFieldVar> fields = new ArrayList<JFieldVar>(jdc.fields().values());
            for (JFieldVar field : fields)
            {
                // never do something with serialVersionUID if it exists.
                if (!field.name().equalsIgnoreCase("serialVersionuid"))
                {
                    // only try to change members that are not private
                    if (field.mods().getValue() != JMod.PRIVATE)
                    {
                        // since there is no way to change the visibilty, remove the field an recreate it
                        jdc.removeField(field);
                        jdc.field(JMod.PRIVATE, field.type(), field.name());

                    }
                }
            }

        }
        return true;
    }

}

如果你愿意随意使用想要。

Feel free to use this if you want.

这篇关于为什么JAXB生成的类具有受保护的成员?如何更改它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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