2011-05-23 88 views
0

我需要將Eclipse JDT集成到一些基於java.lang.reflect的現有API中。我的問題是:是否有現有的接口或適配器?做這個的最好方式是什麼?任何人都可以指向我的教程來做到這一點?Eclipse JDT適配器到java.lang.reflect

例如,我需要從org.eclipse.jdt.core.dom.IMethodBinding檢索java.lang.reflect.Method

同樣,我需要從org.eclipse.jdt.core.dom.Typeorg.eclipse.jdt.core.dom.ITypeBinding得到java.lang.Class。我發現,這可以通過以下方式實現:

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

當然,這是一個非常簡單的解決方案,假設類已經存在的類路徑,並通過JDT API沒有改變 - 所以它是遠遠不夠完善。但應該指出,這兩個假設確實適用於我的具體情況。

回答

0

鑑於該類已經存在於類路徑中,並且不會通過JDT API進行實質性更改,我自己實現了一些內容。

例如一個IMethodBinding可以轉化爲用下面的代碼一個Method

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也解決了第二個問題。希望這有助於任何人。