2017-04-02 185 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);