经过一些严格的调查后,我得出的结论是,如果没有 AST 相关信息,就不可能捕获方法内部的变化。因此,我一直在寻找最有效的方法来存储所需的最少信息,以及比较这些信息的最合适的方法。
这是我提出的解决方案,根据几天的测试,它似乎足够有效,可以在每个ElementChangedEvent
.
// during each user-invoked-compile, these are processed and cleared
private static HashMap<String, IMethod> added = new HashMap<String, IMethod>();
private static HashMap<String, IMethod> changed = new HashMap<String, IMethod>();
private static HashMap<String, IMethod> removed = new HashMap<String, IMethod>();
// this persists through out the entire session
private static HashMap<String, ASTNode> subtrees = new HashMap<String, ASTNode>();
private static void attachModelPart() {
JavaCore.addElementChangedListener(new IElementChangedListener() {
@Override
public void elementChanged(ElementChangedEvent event) {
... // added and removed IMethod handling
IJavaElementDelta delta = event.getDelta();
if (delta.getElement() instanceof CompilationUnit) {
delta.getCompilationUnitAST().accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
String mName = ((TypeDeclaration) node.getParent()).getName()
.getFullyQualifiedName() + "." + node.getName().getFullyQualifiedName();
// Finding match for this methods name(mName) in saved method subtrees...
boolean methodHasChanged = false;
if (subtrees.containsKey(mName)) {
// Found match
// Comparing new subtree to one saved during an earlier event (using ASTNode.subtreeMatch())
methodHasChanged = !node.subtreeMatch(new ASTMatcher(), subtrees.get(mName));
} else {
// No earlier entry found, definitely changed
methodHasChanged = true;
}
if (methodHasChanged) {
// "changed" is a HashMap of IMethods that have been earlierly identified as changed
// "added" works similarly but for added methods (using IJavaElementDelta.getAddedChildren())
if (!changed.containsKey(mName) && !added.containsKey(mName)) {
// Method has indeed changed and is not yet queued for further actions
changed.put(mName, (IMethod) node.resolveBinding().getJavaElement());
}
}
// "subtrees" must be updated with every method's AST subtree in order for this to work
subtrees.put(mName, node);
// continue visiting after first MethodDeclaration
return true;
}
});
}
}
}
}
欢迎评论!