Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do JAXB generated classes have protected members and how can I change this?

Tags:

java

xml

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.

My search has come up empty.

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?

like image 382
tom Avatar asked Feb 21 '12 12:02

tom


1 Answers

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.

like image 61
tom Avatar answered Nov 12 '22 04:11

tom