0

我需要将Eclipse JDT集成到一些基于java.lang.reflect的现有 API 中。我的问题是:是否有现有的接口或适配器?做这个的最好方式是什么?谁能指点我一个教程来做到这一点?

例如,我需要java.lang.reflect.Methodorg.eclipse.jdt.core.dom.IMethodBinding.

同样,我需要java.lang.Class从 aorg.eclipse.jdt.core.dom.Typeorg.eclipse.jdt.core.dom.ITypeBinding. 我发现这可以通过以下方式实现:

Class<?> clazz = Class.forName(typeBinding.getBinaryName());

当然,这是一个非常简单的解决方案,它假定类已经存在于类路径中并且没有通过 JDT API 进行更改——因此它远非完美。但应该注意的是,这两个假设确实适用于我的具体情况。

4

1 回答 1

0

鉴于该类已经存在于类路径中并且没有通过 JDT API 进行实质性更改,因此我自己实现了一些东西。

例如,IMethodBinding可以Method使用以下代码将 a 转换为 a:

    IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
    Class<?> clazz = retrieveTypeClass(methodBinding.getDeclaringClass());
    Class<?>[] paramClasses = new Class<?>[methodInvocation.arguments().size()];
    for (int idx = 0; idx < methodInvocation.arguments().size(); idx++) {
        ITypeBinding paramTypeBinding = methodBinding.getParameterTypes()[idx];
        paramClasses[idx] = retrieveTypeClass(paramTypeBinding);
    }
    String methodName = methodInvocation.getName().getIdentifier();
    Method method;
    try {
        method = clazz.getMethod(methodName, paramClasses);
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }

private Class<?> retrieveTypeClass(Object argument) {
    if (argument instanceof SimpleType) {
        SimpleType simpleType = (SimpleType) argument;
        return retrieveTypeClass(simpleType.resolveBinding());
    }
    if (argument instanceof ITypeBinding) {
        ITypeBinding binding = (ITypeBinding) argument;
        String className = binding.getBinaryName();
        if ("I".equals(className)) {
            return Integer.TYPE;
        }
        if ("V".equals(className)) {
            return Void.TYPE;
        }
        try {
            return Class.forName(className);
        } catch (Exception exc) {
            throw new RuntimeException(exc);
        }
    }
    if (argument instanceof IVariableBinding) {
        IVariableBinding variableBinding = (IVariableBinding) argument;
        return retrieveTypeClass(variableBinding.getType());
    }
    if (argument instanceof SimpleName) {
        SimpleName simpleName = (SimpleName) argument;
        return retrieveTypeClass(simpleName.resolveBinding());
    }
    throw new UnsupportedOperationException("Retrieval of type " + argument.getClass() + " not implemented yet!");
}

请注意,该方法retrieveTypeClass还解决了第二个问题。希望这对任何人都有帮助。

于 2011-05-25T11:49:03.783 回答