使用 javassist 添加方法参数名称 [英] Adding method parameter name with javassist

查看:146
本文介绍了使用 javassist 添加方法参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当方法参数名称不存在时,如何将方法参数名称添加到方法中?

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?

推荐答案

Javassist 不允许删除方法或字段,但它允许更改名称.所以如果一个方法不再需要,它应该通过调用 setName() 和CtMethod 中声明的 setModifiers().

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 不允许添加现有方法的额外参数.而不是做即,一种接收额外参数以及其他参数的新方法参数应该添加到同一个类中.例如,如果你想向方法添加额外的 int 参数 newZ:

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;}

在一个 Point 类中,那么你应该在 Point 类中添加以下方法:

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

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

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

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

}

有关更多信息,请查看此https://jboss-javassist.github.io/javassist/tutorial/tutorial2.html

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

这篇关于使用 javassist 添加方法参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆