2017-04-02 31 views
0

的方法這是原始的方法:Javassist進行復制與註釋

@GET 
    @Produces({"application/json"}) 
    public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui) 
    { 
    return null 
    } 

我想複製這種方法,但添加一個新字符串參數,而新方法的註釋是和以前一樣,這樣的:

@GET 
    @Produces({"application/json"}) 
    public Response getTermClouds(@Context SecurityContext secCtxt, @Context UriInfo ui,String newParam) 
    { 
    return null 
    } 

我用了Javassist做到這一點,我我想知道我添加一個「搞定」的註釋,然後添加一個「生產」的註釋,因爲可能有很多其他註釋它們unkown.How做它作爲一種常見的方式?

回答

0

當您嘗試向方法中添加新參數時,Javassist不允許向現有方法添加額外參數,而不是這樣做,接收額外參數以及其他參數的新方法將添加到同一班。

CtMethod對象的副本可以通過CtNewMethod.copy()獲取。

嘗試this創建您以前的方法的副本。你能解釋一下你想用註釋完成什麼嗎?

+0

其實,這是一個JAX-RS類名爲「路徑」。我沒有這個源代碼,我想一個參數「@context HttpSevletRequest請求」添加到註釋我可以從中得到真正的路徑。雖然我可以複製一個新的方法,但它沒有註釋。或者從一個字符串解析一個新的方法,也沒有註釋,也沒有泛型類型。 – user6630815

+0

@ user6630815您可以在運行時向註釋添加註釋。 –

0

我意識到這是現在老了,但我遇到了同樣的問題,試圖向Spring web處理程序方法添加參數,並且我已經弄明白了。您需要將舊類的屬性複製到新類。您也可能希望將其從舊版本中移除以防止可能的衝突。代碼如下所示:

//Create a new method with the same name as the old one 
CtMethod mNew = CtNewMethod.copy(mOrig, curClass, null); 

//Copy all attributes from the old method to the new one. This includes annotations 
for(Object attribute: mOrig.getMethodInfo().getAttributes()) { 
    m.getMethodInfo().addAttribute((AttributeInfo)attribute); 
} 

//Remove the method and parameter annotations from the old method 
mOrig.getMethodInfo().removeAttribute(AnnotationsAttribute.visibleTag); 
mOrig.getMethodInfo().removeAttribute(ParameterAnnotationsAttribute.visibleTag); 

//Add the new String parameter to the new method 
m.addParameter(cp.getOrNull("java.lang.String")); 

//Add a new empty annotation entry for the new parameter (not sure this part is necessary for you. 
//In my case, I was adding a new parameter to the beginning, so the old ones needed to be offset. 
ParameterAnnotationsAttribute paa = (ParameterAnnotationsAttribute)m.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag); 
Annotation[][] oldAnnos = paa.getAnnotations(); 
Annotation[][] newAnnos = new Annotation[oldAnnos.length + 1][]; 
newAnnos[oldAnnos.length] = new Annotation[] {}; 
System.arraycopy(oldAnnos, 0, newAnnos, 0, oldAnnos.length); 
paa.setAnnotations(newAnnos); 

//Rename the old method and add the new one to the class 
mOrig.setName(mOrig.getName() + "_replaced"); 
curClass.addMethod(m);