Use JDT to get full method name

只谈情不闲聊 提交于 2019-12-05 08:45:38

You can get the Fully qualified name for the type using

method.getDeclaringType().getFullyQualifiedName();

This is probably easier than accessing the package from the compilation unit. The rest of you function looks correct.

One small point: you should use StringBuilder to build up the string instead of adding to a standard String. Strings are immutable so addition creates loads of unrecesary temparary objects.

private static String getMethodFullName(IMethod iMethod)
{
        StringBuilder name = new StringBuilder();
        name.append(iMethod.getDeclaringType().getFullyQualifiedName());
        name.append(".");
        name.append(iMethod.getElementName());
        name.append("(");

        String comma = "";
        for (String type : iMethod.getParameterTypes()) {
                name.append(comma);
                comma = ", ";
                name.append(type);
        }
        name.append(")");

        return name.toString();
}

Thanks to iain and some more research I have come up with this solution. It seems like something like this should be built into the JDT....

import org.eclipse.jdt.core.Signature;

private static String getMethodFullName(IMethod iMethod)
{
        StringBuilder name = new StringBuilder();
        name.append(iMethod.getDeclaringType().getFullyQualifiedName());
        name.append(".");
        name.append(iMethod.getElementName());
        name.append("(");

        String comma = "";
        String[] parameterTypes = iMethod.getParameterTypes();
        try {
            String[] parameterNames = iMethod.getParameterNames();
            for (int i=0; i<iMethod.getParameterTypes().length; ++i) {
                name.append(comma);
                name.append(Signature.toString(parameterTypes[i]));
                name.append(" ");
                name.append(parameterNames[i]);
                comma = ", ";
            }
        } catch (JavaModelException e) {
        }

        name.append(")");

        return name.toString();
}

I am not sure it would take into account all cases (method within an internal class, an anonymous class, with generic parameters...)

When it comes to methods signatures, the classes to look into are:

You need to get the jdt.core.dom.IMethodBinding, from which you can extract all what you need.

If you have a MethodInvocation, you can:

//MethodInvocation node
ITypeBinding type = node.getExpression().resolveTypeBinding();
IMethodBinding  method=node.resolveMethodBinding();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!