XJC generates a different type of field (effect on the get method)

Using the latest JAXB (Metro) and building Java with XJC ....

You want (as other users asked) to generate java.util.Set as a type for fields representing unlimited sequences. It seems that this type of field is captured by the XJC as UntypedListField, and the default behavior is to generate java.util.List (getter only). If I do something similar to a collector-injector plugin and adjust the field type, for example

 public boolean run(Outline model, Options opt, ErrorHandler errorHandler) {
    for (ClassOutline co : model.getClasses()) {
       FieldOutline[] fo = co.getDeclaredFields();

       for ...
          if ((fo[i] instanceof UntypedListField)) {
            --> DO SOMETHING WITH THIS FIELD
          }
    }
 }

How do people set up a type or is it easier to build a new field and then replace it in a set of declared fields in the class loop? How to mess with the type of field affects the generation of the get method on the property?

+3
source share
1 answer

, XJC-. , . --> DO SOMETHING WITH THIS FIELD .

, fo[i] ( f). Set JType. , , f setType:

JType inner = ((JClass)f.type()).getTypeParameters().get(0);
JType setType = co.parent().getCodeModel().ref(Set.class).narrow(inner);
f.type(setType);

narrow() .

, , XJC, . , . .

replaceGetter()

private void replaceGetter(ClassOutline co, JFieldVar f, JType inner) {
    //Create the method name
    String get = "get";
    String name  = f.name().substring(0, 1).toUpperCase() 
            + f.name().substring(1);
    String methodName = get+name;

    //Create HashSet JType
    JType hashSetType = co.parent().getCodeModel().ref(HashSet.class).narrow(inner);

    //Find and remove Old Getter!
    JMethod oldGetter = co.implClass.getMethod(methodName, new JType[0]);
    co.implClass.methods().remove(oldGetter);

    //Create New Getter
    JMethod getter = co.implClass.method(JMod.PUBLIC, f.type(), methodName);

    //Create Getter Body -> {if (f = null) f = new HashSet(); return f;}
    getter.body()._if(JExpr.ref(f.name()).eq(JExpr._null()))._then()
    .assign(f, JExpr._new(hashSetType));

    getter.body()._return(JExpr.ref(f.name()));
}

, .

+1

Source: https://habr.com/ru/post/1795776/


All Articles