2011-03-02 68 views
3

采用最新JAXB(地铁),并与XJC生成Java ....XJC产生另一个字段类型(对GET方法效果)

要(其它用户要求)产生java.util.Set中的作为代表无限序列的字段的类型。看起来这种类型的字段被XJC捕获为UntypedListField,默认行为是生成java.util.List(只有getter)。如果我做类似集合二传手注射器插件的东西,调整字段的类型像

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

人们如何调整型或者是更容易构造一个新的领域,然后在设定的声明的字段的替换在课堂大纲?如何处理字段的类型会影响属性上get方法的生成?

+0

你可以发布你的模式的相关位? – 2011-07-17 23:40:37

回答

1

看起来像你要为自己的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())); 
} 

希望对您有所帮助。

相关问题