Eclipse JDT适配器到java.lang.reflect

| 我需要将Eclipse JDT集成到一些基于java.lang.reflect的现有API中。我的问题是:是否有现有的接口或适配器?做这个的最好方式是什么?谁能指出我的教程来做到这一点? 例如,我需要从
org.eclipse.jdt.core.dom.IMethodBinding
中检索
java.lang.reflect.Method
。 同样,我需要从
org.eclipse.jdt.core.dom.Type
org.eclipse.jdt.core.dom.ITypeBinding
得到
java.lang.Class
。我发现可以通过以下方法实现:
Class<?> clazz = Class.forName(typeBinding.getBinaryName());
当然,这是一个非常简单的解决方案,它假定该类已经存在于类路径中,并且不会通过JDT API进行更改-因此,它远非完美。但是应该指出,这两个假设确实适用于我的具体情况。     
已邀请:
鉴于该类已经存在于类路径中,并且不会通过JDT API进行实质性更改,因此我自己实现了一些东西。 例如,可以使用以下代码将“ 6”转换为“ 7”:
    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!\");
}
注意,方法“ 9”也解决了第二个问题。希望这对任何人有帮助。     

要回复问题请先登录注册