Adding method parameter name with javassist

故事扮演 提交于 2019-12-11 07:44:08

问题


How can I add method parameter names to a method, when none exists?

There are some examples on how to retrieve these names, if they exist, with a method like this:

CtMethod m;
CodeAttribute codeAttribute = m.getMethodInfo().getCodeAttribute();
if (codeAttribute != null) {
    LocalVariableAttribute table = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    if (table != null)
        for (int i = 0; i < table.tableLength(); i++)
            m.getMethodInfo().getConstPool().getUtf8Info(table.nameIndex(i));
} 

This will give all the parameter names of a method, if they exist.

How can I do the reverse?


回答1:


Javassist does not allow to remove a method or field, but it allows to change the name. So if a method is not necessary any more, it should be renamed and changed to be a private method by calling setName() and setModifiers() declared in CtMethod.

Javassist does not allow to add an extra parameter to an existing method, either. Instead of doing that, a new method receiving the extra parameter as well as the other parameters should be added to the same class. For example, if you want to add an extra int parameter newZ to a method:

void move(int newX, int newY) { x = newX; y = newY; }

in a Point class, then you should add the following method to the Point class:

void move(int newX, int newY, int newZ) {

// do what you want with newZ.
move(newX, newY); 

}

for more information, check this https://jboss-javassist.github.io/javassist/tutorial/tutorial2.html



来源:https://stackoverflow.com/questions/45994958/adding-method-parameter-name-with-javassist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!