Adding method parameter name with javassist

2019-08-06 23:12发布

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条回答
何必那么认真
2楼-- · 2019-08-06 23:56

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

查看更多
登录 后发表回答