我有一个IResourceChangeListener
来监听工作区中的更改。但是我无法仅返回触发IResourceChangeEvent
的类。
这就是我目前所拥有的:
public class ResourceChangeListener implements IResourceChangeListener {
private Logger logger = Logger.getAnonymousLogger();
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta[] allChanges = event.getDelta().getAffectedChildren();
for(IResourceDelta delta : allChanges) {
// only check projects when there are actual changes (4 = CHANGED)
if(delta.getKind() == 4) {
try {
IPackageFragment[] packages = JavaCore.create(delta.getResource().getProject()).getPackageFragments();
IPackageFragment myPackage = null;
// get current project package
for(IPackageFragment currentPackage : packages) {
if(currentPackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
myPackage = currentPackage;
}
}
// get all compilation units from package and parse them for new achievements
ICompilationUnit[] units = myPackage.getCompilationUnits();
for(ICompilationUnit unit : units) {
// do something with ICompilationUnits
}
}
catch (JavaModelException e) {
// catch exception here
}
}
}
}
}
此尝试返回受影响的整个包。因此,我只能遍历其中的所有ICompilationUnits。
与此相反,我的目标是获得实际发生变化的课程。这有可能吗?
答案 0 :(得分:0)
感谢greg,我得到了解决方案。
我的初级课程现在看起来像这样:
public class ResourceChangeListener implements IResourceChangeListener {
private Logger logger = Logger.getAnonymousLogger();
public void resourceChanged(IResourceChangeEvent event) {
IResourceDelta[] allChanges = event.getDelta().getAffectedChildren();
for(IResourceDelta delta : allChanges) {
if(delta.getKind() == 4) { // only check projects when there are actual changes (4 = CHANGED)
try {
// visits resource deltas
ResourceDeltaVisitor resourceDeltaVisitor = new ResourceDeltaVisitor();
delta.accept(resourceDeltaVisitor);
ArrayList<IResource> changedClasses = resourceDeltaVisitor.getChangedResources();
for(IResource changedClass : changedClasses) {
ICompilationUnit iCompilationUnit = (ICompilationUnit)JavaCore.create(changedClass);
// do something with ICompilationUnits...
}
}
catch (CoreException e1) {
// catch exception here
}
}
}
}
}
我的ResourceDeltaVisitor
课程如下:
public class ResourceDeltaVisitor implements IResourceDeltaVisitor {
private ArrayList<IResource> changedClasses = new ArrayList<IResource>();
public boolean visit(IResourceDelta delta) {
IResource res = delta.getResource();
if(res.getName().endsWith(".java")) {
addResource(res);
}
return true; // visit the children
}
public ArrayList<IResource> getChangedResources() {
return changedClasses;
}
private void addResource(IResource res) {
changedClasses.add(res);
}
}
这不是最佳解决方案,但它对我有用。