2017-04-07 71 views
0

理想情況下,我想將一些生成的代碼添加到ObjectFactory類。如果這是不可能的,我想使用生成的ObjectFactory作爲另一個生成的方法中的參數。如何從xjc插件代碼中引用由xjc生成的ObjectFactory類?

這種情況會是這個樣子:

import com.sun.tools.xjc.Plugin; 
import com.sun.tools.xjc.outline.Outline; 
import com.sun.tools.xjc.outline.ClassOutline; 
import com.sun.codemodel.JMethod; 
import com.sun.codemodel.JMod; 

public class App extends Plugin { 
    ... 
    private static void generateMyMethod(Outline model, ClassOutline classOutline) { 
     //somehow get 'objectFactoryInstance' 
     JMethod method = classOutline.implClass.method(JMod.PUBLIC | JMod.FINAL | JMod.STATIC, Void.class, "useObjectFactory") 
       .param(objectFactoryInstance, "input")); 
    } 
} 

和生成的代碼應該是這樣的:

public final static void useObjectFactory(ObjectFactory input) { 
    //stuff happens here 
} 

的問題是我如何從我的XJC內到達生成的ObjectFactory插入?

其他的生成類都是這樣的訪問,除了的ObjectFactory:

@Override 
public boolean run(Outline model, Options opt, ErrorHandler errorHandler) throws SAXException { 
    for (ClassOutline classOutline : model.getClasses()) { 
     //do something with the generated class 
    } 
} 

回答

0

我無法訪問生成的ObjectFactory類像我訪問其他的生成類。所以現在我正在生成假定將生成ObjectFactory的代碼。基於這個假設,我用我想要的方法創建另一個班級。

import com.sun.codemodel.JBlock; 
import com.sun.codemodel.JExpr; 
import com.sun.codemodel.JExpression; 
import com.sun.codemodel.JMethod; 
import com.sun.codemodel.JMod; 
import com.sun.codemodel.JVar; 
import com.sun.tools.xjc.outline.ClassOutline; 

//... 
    public void generateMethodThatUsesObjectFactory(ClassOutline classOutline) { 
     JMethod method = classOutline.implClass.method(JMod.PUBLIC | 
     JMod.FINAL, model.getModel().codeModel.VOID, "useObjectFactory"); 
     JVar objectFactory = method.param(model.getModel().codeModel.ref(Object.class), "input"); 
     JExpression objectFactoryCast = JExpr.cast(model.getModel().codeModel.ref("ObjectFactory"), objectFactory); 
     JBlock body = method.body(); 
     //add the objectFactory and objectFactoryCast to the method body 
     //... 
    } 
//... 

生成的結果類似於這樣的代碼:

public final static void useObjectFactory(Object input) { 
    JAXBElement<SomeType> je = ((ObjectFactory) input).callMethodOfObjectFactory(); 
    //... 
} 

我不認爲這是一個理想的方法,但它的作品。爲了在某​​個時間點得到更好的答案,我現在不會接受我自己的答案。