1
votes

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
If I may, why would you change the name of parameter in a compiled method? - rakwaht
Practically I don't want to change it. I want to add it if it does not exist. The original concept is that, the setBody(String) method removes not only the code but everything from a method, including the parameter names, see github.com/jboss-javassist/javassist/issues/146 . I want to reverse this bad artifact. - Panayotis
I get the buggy situation, however I still don't get why you need this info to be attached to a compiled class. First I think that those info are not always persent but they are based on the compilation settings and second you can access with Javassist all the parameters just using several identifiers starting with $ have special meaning. take a look here jboss-javassist.github.io/javassist/tutorial/tutorial2.html - rakwaht
Yes, I understand what you mean, but it is a strong requirement for a specific library, which in general there is no problem but in some edge cases this info needs to be preserved. Thanks for the tip. - Panayotis

1 Answers

0
votes

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