diff options
336 files changed, 3619 insertions, 4045 deletions
diff --git a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/BrowserManager.java b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/BrowserManager.java index 84bb63683..e59c16103 100644 --- a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/BrowserManager.java +++ b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/BrowserManager.java @@ -183,9 +183,9 @@ public class BrowserManager { private List<String> getConfigFilesList(String[] configFiles) { List<String> configs = new ArrayList<String>(); - for (int i = 0; i < configFiles.length; i++) { - if (configFiles[i].endsWith(BuildConfigManager.CONFIG_FILE_SUFFIX)) { - configs.add(configFiles[i]); + for (String configFile : configFiles) { + if (configFile.endsWith(BuildConfigManager.CONFIG_FILE_SUFFIX)) { + configs.add(configFile); } } return configs; diff --git a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/Main.java b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/Main.java index 76c1b50e2..6d56a6f2a 100644 --- a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/Main.java +++ b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/Main.java @@ -42,8 +42,8 @@ public class Main { return false; } int numConfigFiles = 0; - for (int i = 0; i < args.length; i++) { - if ((null != args[i]) && args[i].endsWith(".lst")) { + for (String arg : args) { + if ((null != arg) && arg.endsWith(".lst")) { numConfigFiles++; } } diff --git a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/core/BrowserCompilerConfiguration.java b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/core/BrowserCompilerConfiguration.java index 35f676e1b..0295a9a24 100644 --- a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/core/BrowserCompilerConfiguration.java +++ b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/core/BrowserCompilerConfiguration.java @@ -43,8 +43,7 @@ public class BrowserCompilerConfiguration implements ICompilerConfiguration { classpath.append(userPath); } List<File> outputDirs = getOutputLocationManager().getAllOutputLocations(); - for (Iterator<File> iterator = outputDirs.iterator(); iterator.hasNext();) { - File dir = (File) iterator.next(); + for (File dir : outputDirs) { classpath.append(File.pathSeparator + dir.getAbsolutePath() + File.pathSeparator); } classpath.append(System.getProperty("java.class.path", ".")); diff --git a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/ui/swing/MessageHandlerPanel.java b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/ui/swing/MessageHandlerPanel.java index fa24f709f..d3abd95eb 100644 --- a/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/ui/swing/MessageHandlerPanel.java +++ b/ajbrowser/src/main/java/org/aspectj/tools/ajbrowser/ui/swing/MessageHandlerPanel.java @@ -73,8 +73,8 @@ public class MessageHandlerPanel extends JPanel { private void createList(List<IMessage> messages) { list = new JList(); listModel = new DefaultListModel(); - for (Iterator<IMessage> iterator = messages.iterator(); iterator.hasNext();) { - listModel.addElement(iterator.next()); + for (IMessage message : messages) { + listModel.addElement(message); } } diff --git a/ajde.core/src/main/java/org/aspectj/ajde/core/internal/AjdeCoreBuildManager.java b/ajde.core/src/main/java/org/aspectj/ajde/core/internal/AjdeCoreBuildManager.java index 08d3ee377..a83ab5be2 100644 --- a/ajde.core/src/main/java/org/aspectj/ajde/core/internal/AjdeCoreBuildManager.java +++ b/ajde.core/src/main/java/org/aspectj/ajde/core/internal/AjdeCoreBuildManager.java @@ -250,11 +250,11 @@ public class AjdeCoreBuildManager { args = new String[l.size() + xmlfiles.size() + 1]; // TODO speedup int p = 0; - for (int i = 0; i < l.size(); i++) { - args[p++] = l.get(i); + for (String s : l) { + args[p++] = s; } - for (int i = 0; i < xmlfiles.size(); i++) { - args[p++] = xmlfiles.get(i); + for (String xmlfile : xmlfiles) { + args[p++] = xmlfile; } args[p++] = "-xmlConfigured"; } else { diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/AjdeCoreTestCase.java b/ajde.core/src/test/java/org/aspectj/ajde/core/AjdeCoreTestCase.java index 052d547c6..eafa22f04 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/AjdeCoreTestCase.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/AjdeCoreTestCase.java @@ -85,8 +85,7 @@ public abstract class AjdeCoreTestCase extends TestCase { String contents[] = from.list(); if (contents == null) return; - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(from, string); File t = new File(to, string); @@ -141,8 +140,8 @@ public abstract class AjdeCoreTestCase extends TestCase { public List<String> getSourceFileList(String[] files) { List<String> sourceFiles = new ArrayList<String>(); - for (int i = 0; i < files.length; i++) { - sourceFiles.add(getAbsoluteProjectDir() + File.separator + files[i]); + for (String file : files) { + sourceFiles.add(getAbsoluteProjectDir() + File.separator + file); } return sourceFiles; } diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/TestCompilerConfiguration.java b/ajde.core/src/test/java/org/aspectj/ajde/core/TestCompilerConfiguration.java index 57d1ce73a..e8432c8cf 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/TestCompilerConfiguration.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/TestCompilerConfiguration.java @@ -116,17 +116,17 @@ public class TestCompilerConfiguration implements ICompilerConfiguration { /* Allow the user to override the testProjectPath by using sourceRoots */ File[] srcBase = new File[] { new File(projectPath + File.separator + srcDirName) }; - for (int j = 0; j < srcBase.length; j++) { - File[] fromResources = FileUtil.listFiles(srcBase[j], new FileFilter() { + for (File file : srcBase) { + File[] fromResources = FileUtil.listFiles(file, new FileFilter() { public boolean accept(File pathname) { String name = pathname.getName().toLowerCase(); return !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj") && !name.endsWith(".lst") && !name.endsWith(".jar"); } }); - for (int i = 0; i < fromResources.length; i++) { - String normPath = FileUtil.normalizedPath(fromResources[i], srcBase[j]); - sourcePathResources.put(normPath, fromResources[i]); + for (File fromResource : fromResources) { + String normPath = FileUtil.normalizedPath(fromResource, file); + sourcePathResources.put(normPath, fromResource); } } diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/AjConfigTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/AjConfigTest.java index eb7d67b9c..15d2ff696 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/AjConfigTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/AjConfigTest.java @@ -135,8 +135,7 @@ public class AjConfigTest extends AjdeCoreTestCase { compilerConfig.setSourcePathResources(m); AjBuildConfig buildConfig = genAjBuildConfig(); Map<String, File> found = buildConfig.getSourcePathResources(); - for (Iterator<String> i = found.keySet().iterator(); i.hasNext();) { - String resource = i.next(); + for (String resource : found.keySet()) { assertEquals("expected to find resource with name newFile.txt but " + "found " + resource, "newFile.txt", resource); File from = buildConfig.getSourcePathResources().get(resource); assertEquals("expected to find resource with file " + getWorkingDir() + "but found " + from, getWorkingDir(), from); diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/InpathTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/InpathTest.java index af1040e5f..0696aa908 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/InpathTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/InpathTest.java @@ -294,8 +294,7 @@ public class InpathTest extends AjdeCoreTestCase { File binBase = openFile(outdirName); String[] toResources = FileUtil.listFiles(binBase); - for (int i = 0; i < toResources.length; i++) { - String fileName = toResources[i]; + for (String fileName : toResources) { if (fileName.indexOf("CVS") == -1) { boolean b = expectedOutdirContents.remove(fileName); assertTrue("Extraneous resources: " + fileName, b); @@ -308,8 +307,8 @@ public class InpathTest extends AjdeCoreTestCase { private void listSourceResources(String indirName, Set<String> resources) { File srcBase = openFile(indirName); File[] fromResources = FileUtil.listFiles(srcBase, aspectjResourceFileFilter); - for (int i = 0; i < fromResources.length; i++) { - String name = FileUtil.normalizedPath(fromResources[i], srcBase); + for (File fromResource : fromResources) { + String name = FileUtil.normalizedPath(fromResource, srcBase); // System.err.println("Checking "+name); if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { resources.add(name); diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ResourceCopyTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ResourceCopyTest.java index c75da5b04..b6f44ae7d 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ResourceCopyTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ResourceCopyTest.java @@ -155,8 +155,8 @@ public class ResourceCopyTest extends AjdeCoreTestCase { HashSet<String> resources = new HashSet<>(); listSourceResources(indirName, resources); - for (int i = 0; i < toResources.length; i++) { - String fileName = FileUtil.normalizedPath(toResources[i], binBase); + for (File toResource : toResources) { + String fileName = FileUtil.normalizedPath(toResource, binBase); boolean b = resources.remove(fileName); assertTrue("Extraneous resources: " + fileName, b); } @@ -167,8 +167,8 @@ public class ResourceCopyTest extends AjdeCoreTestCase { private void listSourceResources(String indirName, Set<String> resources) { File srcBase = openFile(indirName); File[] fromResources = FileUtil.listFiles(srcBase, aspectjResourceFileFilter); - for (int i = 0; i < fromResources.length; i++) { - String name = FileUtil.normalizedPath(fromResources[i], srcBase); + for (File fromResource : fromResources) { + String name = FileUtil.normalizedPath(fromResource, srcBase); if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) { resources.add(name); } @@ -263,12 +263,12 @@ public class ResourceCopyTest extends AjdeCoreTestCase { File binBase = openFile(outdirName); File[] toResources = FileUtil.listFiles(binBase, aspectjResourceFileFilter); - for (int i = 0; i < toResources.length; i++) { - String fileName = FileUtil.normalizedPath(toResources[i], binBase); + for (File toResource : toResources) { + String fileName = FileUtil.normalizedPath(toResource, binBase); /* Ensure we copied the right JAR manifest */ if (fileName.equalsIgnoreCase("meta-inf/Manifest.mf")) { - byte[] outManifest = FileUtil.readAsByteArray(toResources[i]); + byte[] outManifest = FileUtil.readAsByteArray(toResource); assertTrue("Wrong manifest has been copied", Arrays.equals(inManifest, outManifest)); } boolean b = resources.remove(fileName); diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ShowWeaveMessagesTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ShowWeaveMessagesTest.java index c13462620..bc4263f4e 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ShowWeaveMessagesTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/ShowWeaveMessagesTest.java @@ -376,8 +376,8 @@ public class ShowWeaveMessagesTest extends AjdeCoreTestCase { // See if the messages match int msgCount = 0; List<TestMessageHandler.TestMessage> l = handler.getMessages(); - for (Iterator<TestMessageHandler.TestMessage> iter = l.iterator(); iter.hasNext();) { - IMessage msg = iter.next().getContainedMessage(); + for (TestMessageHandler.TestMessage testMessage : l) { + IMessage msg = testMessage.getContainedMessage(); if (debugTests) System.out.println("Looking at [" + msg + "]"); if (msg.getKind().equals(IMessage.WEAVEINFO)) { @@ -416,8 +416,8 @@ public class ShowWeaveMessagesTest extends AjdeCoreTestCase { try { fw = new FileWriter(f); List<TestMessageHandler.TestMessage> l = handler.getMessages(); - for (Iterator<TestMessageHandler.TestMessage> iter = l.iterator(); iter.hasNext();) { - IMessage msg = iter.next().getContainedMessage(); + for (TestMessageHandler.TestMessage testMessage : l) { + IMessage msg = testMessage.getContainedMessage(); if (msg.getKind().equals(IMessage.WEAVEINFO)) { fw.write(msg.getMessage() + "\n"); } diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/AsmRelationshipsTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/AsmRelationshipsTest.java index 20b6e346e..4feefedcb 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/AsmRelationshipsTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/AsmRelationshipsTest.java @@ -139,8 +139,7 @@ public class AsmRelationshipsTest extends AjdeCoreTestCase { .findElementForLabel(aspect, IProgramElement.Kind.ADVICE, beforeExec); assertNotNull(beforeExecNode); IRelationship rel = manager.getRelationshipMap().get(beforeExecNode, IRelationship.Kind.ADVICE, relName); - for (Iterator<String> it = rel.getTargets().iterator(); it.hasNext();) { - String currHandle = it.next(); + for (String currHandle : rel.getTargets()) { if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(to)) return; } @@ -186,8 +185,7 @@ public class AsmRelationshipsTest extends AjdeCoreTestCase { // String set = to; IRelationship rel2 = manager.getRelationshipMap().get(clazz, IRelationship.Kind.DECLARE_INTER_TYPE, backRelName); // String handle2 = (String)rel2.getTargets().get(0); - for (Iterator<String> it = rel2.getTargets().iterator(); it.hasNext();) { - String currHandle = it.next(); + for (String currHandle : rel2.getTargets()) { if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(from)) return; } diff --git a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/StructureModelTest.java b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/StructureModelTest.java index 6755ca57e..739daee32 100644 --- a/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/StructureModelTest.java +++ b/ajde.core/src/test/java/org/aspectj/ajde/core/tests/model/StructureModelTest.java @@ -116,8 +116,7 @@ public class StructureModelTest extends AjdeCoreTestCase { } private void testModelIntegrityHelper(IProgramElement node) throws Exception { - for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) { - IProgramElement child = (IProgramElement) it.next(); + for (IProgramElement child : node.getChildren()) { if (node == child.getParent()) { testModelIntegrityHelper(child); } else { @@ -131,8 +130,8 @@ public class StructureModelTest extends AjdeCoreTestCase { public void preProcess(IProgramElement node) { if (node.getChildren() == null) return; - for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) { - if (it.next() == null) + for (IProgramElement iProgramElement : node.getChildren()) { + if (iProgramElement == null) throw new NullPointerException("null child on node: " + node.getName()); } } diff --git a/ajde/src/main/java/org/aspectj/ajde/Ajde.java b/ajde/src/main/java/org/aspectj/ajde/Ajde.java index 2e25e50fc..b458eb9da 100644 --- a/ajde/src/main/java/org/aspectj/ajde/Ajde.java +++ b/ajde/src/main/java/org/aspectj/ajde/Ajde.java @@ -262,8 +262,8 @@ public class Ajde { } else { StringBuffer sb = new StringBuffer(); List outputDirs = compilerConfig.getOutputLocationManager().getAllOutputLocations(); - for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { - File dir = (File) iterator.next(); + for (Object outputDir : outputDirs) { + File dir = (File) outputDir; sb.append(dir.getAbsolutePath() + File.pathSeparator); } classpath = LangUtil.makeClasspath(null, compilerConfig.getClasspath(), sb.toString(), compilerConfig.getOutJar()); diff --git a/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigFileUpdater.java b/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigFileUpdater.java index ac6264436..f3e2154cd 100644 --- a/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigFileUpdater.java +++ b/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigFileUpdater.java @@ -56,20 +56,20 @@ class LstBuildConfigFileUpdater { * Adds an entry to multiple build configuration files. */ public void updateBuildConfigFiles(List buildConfigFiles, List<String> filesToUpdate, boolean addToConfiguration) { - for (int i = 0; i < buildConfigFiles.size(); i++) { - List<String> fileContents = readConfigFile((String) buildConfigFiles.get(i)); + for (Object buildConfigFile : buildConfigFiles) { + List<String> fileContents = readConfigFile((String) buildConfigFile); if (addToConfiguration) { - for (int j = 0; j < filesToUpdate.size(); j++) { - fileContents.add(filesToUpdate.get(j)); + for (String s : filesToUpdate) { + fileContents.add(s); } } else { - for (int k = 0; k < filesToUpdate.size(); k++) { - if (fileContents.contains(filesToUpdate.get(k))) { - fileContents.remove(filesToUpdate.get(k)); + for (String s : filesToUpdate) { + if (fileContents.contains(s)) { + fileContents.remove(s); } } } - writeConfigFile((String) buildConfigFiles.get(i), fileContents); + writeConfigFile((String) buildConfigFile, fileContents); } } @@ -122,16 +122,14 @@ class LstBuildConfigFileUpdater { String fileContentsString = ""; // List filesToWrite = null; Set<String> includedFiles = new HashSet<>(); - for (Iterator<BuildConfigNode> it = importedNodes.iterator(); it.hasNext();) { - BuildConfigNode node = it.next(); + for (BuildConfigNode node : importedNodes) { fileContentsString += '@' + node.getResourcePath() + "\n"; String parentPath = new File(filePath).getParent(); String importedFilePath = parentPath + File.separator + node.getResourcePath(); includedFiles.addAll(getIncludedFiles(importedFilePath, parentPath)); } - for (Iterator<BuildConfigNode> it = files.iterator(); it.hasNext();) { - BuildConfigNode node = it.next(); + for (BuildConfigNode node : files) { if (node.getName().endsWith(".lst") && !node.getResourcePath().startsWith("..")) { fileContentsString += '@'; fileContentsString += node.getResourcePath() + "\n"; @@ -150,8 +148,8 @@ class LstBuildConfigFileUpdater { configParser.parseConfigFile(new File(path)); List<File> files = configParser.getFiles(); List<String> relativeFiles = new ArrayList<String>(); - for (Iterator<File> it = files.iterator(); it.hasNext();) { - relativeFiles.add(relativizePath(it.next().getPath(), rootPath)); + for (File file : files) { + relativeFiles.add(relativizePath(file.getPath(), rootPath)); } return relativeFiles; } catch (ConfigParser.ParseException pe) { diff --git a/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigManager.java b/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigManager.java index 6bd0c23da..feda7df0c 100644 --- a/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigManager.java +++ b/ajde/src/main/java/org/aspectj/ajde/internal/LstBuildConfigManager.java @@ -173,8 +173,8 @@ public class LstBuildConfigManager implements BuildConfigManager { } node.addChild(dir); // boolean foundMatch = false; - for (Iterator it = importedFiles.iterator(); it.hasNext();) { - File importedFile = (File) it.next(); + for (Object file : importedFiles) { + File importedFile = (File) file; if (importedFile.getParentFile().getAbsolutePath().equals(dir2.getAbsolutePath())) { // foundMatch = true; BuildConfigNode importedFileNode = new BuildConfigNode(importedFile.getName(), BuildConfigNode.Kind.FILE_LST, @@ -215,8 +215,8 @@ public class LstBuildConfigManager implements BuildConfigManager { } private void addFilesToDirTree(BuildConfigModel model, List configFiles, List badEntries) { - for (Iterator it = configFiles.iterator(); it.hasNext();) { - String path = (String) it.next(); + for (Object configFile : configFiles) { + String path = (String) configFile; if (path.startsWith("..")) { File file = new File(path); BuildConfigNode node = new BuildConfigNode(file.getName(), BuildConfigNode.Kind.FILE_JAVA, path); diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/StructureSearchManager.java b/ajde/src/main/java/org/aspectj/ajde/ui/StructureSearchManager.java index b6631b3a8..d9e9a0f52 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/StructureSearchManager.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/StructureSearchManager.java @@ -51,8 +51,7 @@ public class StructureSearchManager { } } if (node != null && node.getChildren() != null) { - for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) { - IProgramElement nextNode = it.next(); + for (IProgramElement nextNode : node.getChildren()) { if (nextNode != null) { findMatchesHelper(nextNode, pattern, kind, matches); } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/StructureView.java b/ajde/src/main/java/org/aspectj/ajde/ui/StructureView.java index edbae4698..7d6e4838b 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/StructureView.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/StructureView.java @@ -83,8 +83,8 @@ public abstract class StructureView { } if (node != null && node.getChildren() != null) { - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - IStructureViewNode foundNode = findCorrespondingViewNodeHelper((IStructureViewNode)it.next(), pNode); + for (Object o : node.getChildren()) { + IStructureViewNode foundNode = findCorrespondingViewNodeHelper((IStructureViewNode) o, pNode); if (foundNode != null) return foundNode; } } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewManager.java b/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewManager.java index eb8fdc033..9b23439e4 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewManager.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewManager.java @@ -46,8 +46,8 @@ public class StructureViewManager { public void elementsUpdated(IHierarchy model) { // updating structure views: - for (Iterator it = structureViews.iterator(); it.hasNext();) { - treeViewBuilder.buildView((StructureView) it.next(), (AspectJElementHierarchy) model); + for (Object structureView : structureViews) { + treeViewBuilder.buildView((StructureView) structureView, (AspectJElementHierarchy) model); } } }; @@ -119,8 +119,8 @@ public class StructureViewManager { } } - for (Iterator it = structureViews.iterator(); it.hasNext();) { - StructureView view = (StructureView) it.next(); + for (Object structureView : structureViews) { + StructureView view = (StructureView) structureView; if (!(view instanceof GlobalStructureView) || !recordHistory || defaultFileView == null) { if (node.getKind().equals(IProgramElement.Kind.CODE)) { IProgramElement parentNode = node.getParent(); diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewNodeFactory.java b/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewNodeFactory.java index cb82a65db..43513c14b 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewNodeFactory.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/StructureViewNodeFactory.java @@ -49,14 +49,13 @@ public abstract class StructureViewNodeFactory { IRelationshipMap relMap = (manager == null ? null : manager.getRelationshipMap()); List relationships = (relMap == null ? null : relMap.get(nodeHandle)); if (relationships != null) { - for (Iterator it = relationships.iterator(); it.hasNext();) { - IRelationship rel = (IRelationship) it.next(); + for (Object relationship : relationships) { + IRelationship rel = (IRelationship) relationship; if (rel != null && rel.getTargets().size() > 0) { IStructureViewNode relNode = createRelationship(rel, iconRegistry.getIcon(rel.getKind())); if (relNode != null) { svNode.add(relNode, 0); - for (Iterator it2 = rel.getTargets().iterator(); it2.hasNext();) { - String handle = (String) it2.next(); + for (String handle : rel.getTargets()) { IProgramElement link = Ajde.getDefault().getModel().getHierarchy().findElementForHandle(handle); if (link != null) { IStructureViewNode linkNode = createLink(link, iconRegistry.getStructureIcon(link.getKind(), diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/internal/TreeStructureViewBuilder.java b/ajde/src/main/java/org/aspectj/ajde/ui/internal/TreeStructureViewBuilder.java index 728ed9069..23f999ac8 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/internal/TreeStructureViewBuilder.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/internal/TreeStructureViewBuilder.java @@ -197,8 +197,8 @@ public class TreeStructureViewBuilder { private void sortView(IStructureViewNode node, Comparator<IStructureViewNode> comparator) { if (node == null || node.getChildren() == null) return; Collections.sort(node.getChildren(), comparator); - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - IStructureViewNode nextNode = (IStructureViewNode)it.next(); + for (Object o : node.getChildren()) { + IStructureViewNode nextNode = (IStructureViewNode) o; if (nextNode != null) sortView(nextNode, comparator); } } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/internal/UserPreferencesStore.java b/ajde/src/main/java/org/aspectj/ajde/ui/internal/UserPreferencesStore.java index 572506aed..611af0b4e 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/internal/UserPreferencesStore.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/internal/UserPreferencesStore.java @@ -76,8 +76,8 @@ public class UserPreferencesStore implements UserPreferencesAdapter { @Override public void setProjectMultivalPreference(String name, List values) { String valuesString = ""; - for (Iterator it = values.iterator(); it.hasNext(); ) { - valuesString += (String)it.next() + ';'; + for (Object value : values) { + valuesString += (String) value + ';'; } properties.setProperty(name, valuesString); saveProperties(); diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/javaoptions/JavaCompilerWarningsOptionsPanel.java b/ajde/src/main/java/org/aspectj/ajde/ui/javaoptions/JavaCompilerWarningsOptionsPanel.java index 09d76afc8..51248d6c4 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/javaoptions/JavaCompilerWarningsOptionsPanel.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/javaoptions/JavaCompilerWarningsOptionsPanel.java @@ -67,10 +67,10 @@ public class JavaCompilerWarningsOptionsPanel extends OptionsPanel { public void saveOptions() throws IOException { Set s = warningComboBoxes.entrySet(); - for (Iterator iterator = s.iterator(); iterator.hasNext();) { - Map.Entry entry = (Entry) iterator.next(); + for (Object o : s) { + Entry entry = (Entry) o; String javaOption = (String) entry.getKey(); - JComboBox combo = (JComboBox)entry.getValue(); + JComboBox combo = (JComboBox) entry.getValue(); String value = (String) combo.getSelectedItem(); javaBuildOptions.setOption(javaOption, value); } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserStructureViewToolPanel.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserStructureViewToolPanel.java index 6988536da..6431eb851 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserStructureViewToolPanel.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserStructureViewToolPanel.java @@ -72,8 +72,8 @@ public class BrowserStructureViewToolPanel extends JPanel { view_comboBox = new JComboBox(); view_comboBox.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT); - for (Iterator it = structureViews.iterator(); it.hasNext(); ) { - view_comboBox.addItem(it.next()); + for (Object structureView : structureViews) { + view_comboBox.addItem(structureView); } try { @@ -120,26 +120,26 @@ public class BrowserStructureViewToolPanel extends JPanel { private JPopupMenu createFilterMenu() { JPopupMenu filterMenu = new JPopupMenu(); IProgramElement.Accessibility[] accessibility = IProgramElement.Accessibility.ALL; - for (int i = 0; i < accessibility.length; i++) { - CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(accessibility[i]); - menuItem.setIcon(Ajde.getDefault().getIconRegistry().getAccessibilitySwingIcon(accessibility[i])); + for (IProgramElement.Accessibility value : accessibility) { + CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(value); + menuItem.setIcon(Ajde.getDefault().getIconRegistry().getAccessibilitySwingIcon(value)); filterMenu.add(menuItem); } filterMenu.add(new JSeparator()); IProgramElement.Kind[] kinds = IProgramElement.Kind.ALL; - for (int i = 0; i < kinds.length; i++) { - if (kinds[i].isMember()) { - CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(kinds[i]); - menuItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(kinds[i]).getIconResource()); + for (IProgramElement.Kind kind : kinds) { + if (kind.isMember()) { + CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(kind); + menuItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(kind).getIconResource()); filterMenu.add(menuItem); } } filterMenu.add(new JSeparator()); IProgramElement.Modifiers[] modifiers = IProgramElement.Modifiers.ALL; - for (int i = 0; i < modifiers.length; i++) { - CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(modifiers[i]); + for (IProgramElement.Modifiers modifier : modifiers) { + CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(modifier); filterMenu.add(menuItem); } return filterMenu; @@ -149,10 +149,10 @@ public class BrowserStructureViewToolPanel extends JPanel { JPopupMenu relationsMenu = new JPopupMenu(); java.util.List relations = Ajde.getDefault().getStructureViewManager().getAvailableRelations(); - for (Iterator it = relations.iterator(); it.hasNext(); ) { - IRelationship.Kind relation = (IRelationship.Kind)it.next(); + for (Object o : relations) { + IRelationship.Kind relation = (IRelationship.Kind) o; CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(relation); - menuItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(relation).getIconResource()); + menuItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(relation).getIconResource()); relationsMenu.add(menuItem); } @@ -164,10 +164,10 @@ public class BrowserStructureViewToolPanel extends JPanel { StructureViewProperties.Granularity[] granularity = StructureViewProperties.Granularity.ALL; ButtonGroup group = new ButtonGroup(); - for (int i = 0; i < granularity.length; i++) { - RadioSelectionMenuButton menuItem = new RadioSelectionMenuButton(granularity[i], group); + for (StructureViewProperties.Granularity value : granularity) { + RadioSelectionMenuButton menuItem = new RadioSelectionMenuButton(value, group); orderMenu.add(menuItem); - if (granularity[i].equals(StructureViewProperties.Granularity.MEMBER)) { + if (value.equals(StructureViewProperties.Granularity.MEMBER)) { menuItem.setSelected(true); } } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserView.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserView.java index d41827a41..e9c1196e2 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserView.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserView.java @@ -121,9 +121,9 @@ class BrowserView extends JPanel { public void updateConfigs(java.util.List configsList) { configs_comboBox.removeAllItems(); - for (Iterator it = configsList.iterator(); it.hasNext(); ) { - configs_comboBox.addItem(it.next()); - } + for (Object o : configsList) { + configs_comboBox.addItem(o); + } } public void setSelectedConfig(String config) { diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserViewPanel.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserViewPanel.java index 0b15049b6..a32c53c52 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserViewPanel.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BrowserViewPanel.java @@ -67,12 +67,12 @@ public class BrowserViewPanel extends JPanel implements StructureViewRenderer { public BrowserViewPanel(IconRegistry icons, java.util.List views, StructureViewProperties.Hierarchy visibleViewHierarchy) { try { view_comboBox = new JComboBox(views.toArray()); - for (Iterator it = views.iterator(); it.hasNext(); ) { - StructureViewProperties.Hierarchy hierarchy = (StructureViewProperties.Hierarchy)it.next(); - if (hierarchy == visibleViewHierarchy) { - view_comboBox.setSelectedItem(hierarchy); - } - } + for (Object view : views) { + StructureViewProperties.Hierarchy hierarchy = (StructureViewProperties.Hierarchy) view; + if (hierarchy == visibleViewHierarchy) { + view_comboBox.setSelectedItem(hierarchy); + } + } //GlobalViewProperties visibleView = (GlobalViewProperties)viewProperties.get(visibleViewHierarchy.toString()); treeManager = new StructureTreeManager();//, visibleView); jbInit(); diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BuildConfigPopupMenu.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BuildConfigPopupMenu.java index 7ca7a35fd..0a59ab71a 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/BuildConfigPopupMenu.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/BuildConfigPopupMenu.java @@ -39,23 +39,23 @@ public class BuildConfigPopupMenu extends JPopupMenu { public BuildConfigPopupMenu(final AbstractAction action) { List configFiles = Ajde.getDefault().getBuildConfigManager().getAllBuildConfigFiles(); - for (Iterator it = configFiles.iterator(); it.hasNext(); ) { - final String buildConfig = (String)it.next(); - JMenuItem buildItem = new JMenuItem(buildConfig); - buildItem.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT); - buildItem.addActionListener( - new ActionListener() { - public void actionPerformed(ActionEvent e) { - Ajde.getDefault().getBuildConfigManager().setActiveConfigFile(buildConfig); - // A separate thread is required here because the buildProgresssMonitor - // that monitors the build needs to be in a different thread - // to that which is doing the build (swing threading issues) - Ajde.getDefault().runBuildInDifferentThread(buildConfig, true); - action.actionPerformed(e); - } - }); - buildItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(IProgramElement.Kind.FILE_LST).getIconResource()); - this.add(buildItem); + for (Object configFile : configFiles) { + final String buildConfig = (String) configFile; + JMenuItem buildItem = new JMenuItem(buildConfig); + buildItem.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT); + buildItem.addActionListener( + new ActionListener() { + public void actionPerformed(ActionEvent e) { + Ajde.getDefault().getBuildConfigManager().setActiveConfigFile(buildConfig); + // A separate thread is required here because the buildProgresssMonitor + // that monitors the build needs to be in a different thread + // to that which is doing the build (swing threading issues) + Ajde.getDefault().runBuildInDifferentThread(buildConfig, true); + action.actionPerformed(e); + } + }); + buildItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(IProgramElement.Kind.FILE_LST).getIconResource()); + this.add(buildItem); } } } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/OptionsFrame.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/OptionsFrame.java index 3eb852346..1729ac87a 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/OptionsFrame.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/OptionsFrame.java @@ -160,9 +160,9 @@ public class OptionsFrame extends JFrame { private void saveOptions() { try { Component[] components = main_tabbedPane.getComponents(); - for (int i = 0; i < components.length; i++) { - if (components[i] instanceof OptionsPanel) { - ((OptionsPanel)components[i]).saveOptions(); + for (Component component : components) { + if (component instanceof OptionsPanel) { + ((OptionsPanel) component).saveOptions(); } } } catch (IOException ioe) { diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/StructureViewPanel.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/StructureViewPanel.java index c1435051a..add41298c 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/StructureViewPanel.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/StructureViewPanel.java @@ -63,8 +63,8 @@ public class StructureViewPanel extends JPanel implements StructureViewRenderer public StructureViewPanel(java.util.List structureViews) { // this.structureViews = structureViews; - for (Iterator it = structureViews.iterator(); it.hasNext(); ) { - initView((StructureView)it.next()); + for (Object structureView : structureViews) { + initView((StructureView) structureView); } currentView = (StructureView)structureViews.get(0); structureToolBar_panel = new BrowserStructureViewToolPanel(structureViews, currentView, this); diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/SwingTreeViewNode.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/SwingTreeViewNode.java index 3e3f08935..ef756f6e4 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/SwingTreeViewNode.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/SwingTreeViewNode.java @@ -48,10 +48,10 @@ public class SwingTreeViewNode extends DefaultMutableTreeNode implements IStruct this.kind = Kind.DECLARATION; if (children != null) { - for (Iterator it = children.iterator(); it.hasNext(); ) { - SwingTreeViewNode child = (SwingTreeViewNode)it.next(); + for (Object o : children) { + SwingTreeViewNode child = (SwingTreeViewNode) o; if (StructureViewNodeFactory.acceptNode(programElement, child.getStructureNode())) { - super.add(child); + super.add(child); } } } diff --git a/ajde/src/main/java/org/aspectj/ajde/ui/swing/TreeViewBuildConfigEditor.java b/ajde/src/main/java/org/aspectj/ajde/ui/swing/TreeViewBuildConfigEditor.java index 3d332c865..02f9aaf8f 100644 --- a/ajde/src/main/java/org/aspectj/ajde/ui/swing/TreeViewBuildConfigEditor.java +++ b/ajde/src/main/java/org/aspectj/ajde/ui/swing/TreeViewBuildConfigEditor.java @@ -107,10 +107,9 @@ public class TreeViewBuildConfigEditor extends JPanel implements BuildConfigEdit private ConfigTreeNode buildTree(BuildConfigNode node) { ConfigTreeNode treeNode = new ConfigTreeNode(node); - for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { - BuildConfigNode childNode = (BuildConfigNode)it.next(); - treeNode.add(buildTree(childNode)); - } + for (BuildConfigNode childNode : node.getChildren()) { + treeNode.add(buildTree(childNode)); + } return treeNode; } diff --git a/ajde/src/test/java/org/aspectj/ajde/AjdeTestCase.java b/ajde/src/test/java/org/aspectj/ajde/AjdeTestCase.java index 0c5c5c306..f1d979181 100644 --- a/ajde/src/test/java/org/aspectj/ajde/AjdeTestCase.java +++ b/ajde/src/test/java/org/aspectj/ajde/AjdeTestCase.java @@ -91,8 +91,7 @@ public abstract class AjdeTestCase extends TestCase { String contents[] = from.list(); if (contents == null) return; - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(from, string); File t = new File(to, string); diff --git a/ajde/src/test/java/org/aspectj/ajde/ExtensionTest.java b/ajde/src/test/java/org/aspectj/ajde/ExtensionTest.java index 43d75f8d4..a8ce3d922 100644 --- a/ajde/src/test/java/org/aspectj/ajde/ExtensionTest.java +++ b/ajde/src/test/java/org/aspectj/ajde/ExtensionTest.java @@ -78,8 +78,7 @@ public class ExtensionTest extends AjcTestCase { private IProgramElement getChild(IProgramElement parent, String s) { List<IProgramElement> kids = parent.getChildren(); - for (Iterator<IProgramElement> iter = kids.iterator(); iter.hasNext();) { - IProgramElement element = (IProgramElement) iter.next(); + for (IProgramElement element : kids) { if (element.getName().indexOf(s) != -1) return element; } @@ -97,8 +96,8 @@ public class ExtensionTest extends AjcTestCase { } if (ipe.getChildren() != null) { List kids = ipe.getChildren(); - for (Iterator iter = kids.iterator(); iter.hasNext();) { - IProgramElement element = (IProgramElement) iter.next(); + for (Object kid : kids) { + IProgramElement element = (IProgramElement) kid; findChild(s, element); } } @@ -113,8 +112,8 @@ public class ExtensionTest extends AjcTestCase { System.out.println(ipe.toLabelString());// getName()); if (ipe.getChildren() != null) { List kids = ipe.getChildren(); - for (Iterator iter = kids.iterator(); iter.hasNext();) { - IProgramElement element = (IProgramElement) iter.next(); + for (Object kid : kids) { + IProgramElement element = (IProgramElement) kid; walkit(element, indent + 2); } } diff --git a/ajde/src/test/java/org/aspectj/ajde/ui/StructureViewManagerTest.java b/ajde/src/test/java/org/aspectj/ajde/ui/StructureViewManagerTest.java index 0c1aa53ef..eca56feec 100644 --- a/ajde/src/test/java/org/aspectj/ajde/ui/StructureViewManagerTest.java +++ b/ajde/src/test/java/org/aspectj/ajde/ui/StructureViewManagerTest.java @@ -98,8 +98,7 @@ public class StructureViewManagerTest extends AjdeTestCase { } private void testModelIntegrityHelper(IProgramElement node) throws Exception { - for (Iterator it = node.getChildren().iterator(); it.hasNext();) { - IProgramElement child = (IProgramElement) it.next(); + for (IProgramElement child : node.getChildren()) { if (node == child.getParent()) { testModelIntegrityHelper(child); } else { diff --git a/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestBuildProgressMonitor.java b/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestBuildProgressMonitor.java index 935dcc363..6ccddefc0 100644 --- a/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestBuildProgressMonitor.java +++ b/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestBuildProgressMonitor.java @@ -77,18 +77,18 @@ public class TestBuildProgressMonitor implements IBuildProgressMonitor { } public boolean containsMessage(String prefix,String distinguishingMarks) { - for (Iterator iter = messagesReceived.iterator(); iter.hasNext();) { - String element = (String) iter.next(); + for (Object o : messagesReceived) { + String element = (String) o; if (element.startsWith(prefix) && - element.indexOf(distinguishingMarks)!=-1) return true; + element.indexOf(distinguishingMarks) != -1) return true; } return false; } public void dumpMessages() { System.out.println("ProgressMonitorMessages"); - for (Iterator iter = messagesReceived.iterator(); iter.hasNext();) { - String element = (String) iter.next(); + for (Object o : messagesReceived) { + String element = (String) o; System.out.println(element); } } diff --git a/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestCompilerConfiguration.java b/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestCompilerConfiguration.java index 04a73d2f4..a6fec514d 100644 --- a/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestCompilerConfiguration.java +++ b/ajde/src/test/java/org/aspectj/ajde/ui/utils/TestCompilerConfiguration.java @@ -116,17 +116,17 @@ public class TestCompilerConfiguration implements ICompilerConfiguration { /* Allow the user to override the testProjectPath by using sourceRoots */ File[] srcBase = new File[] { new File(projectPath + File.separator + srcDirName) }; - for (int j = 0; j < srcBase.length; j++) { - File[] fromResources = FileUtil.listFiles(srcBase[j], new FileFilter() { + for (File file : srcBase) { + File[] fromResources = FileUtil.listFiles(file, new FileFilter() { public boolean accept(File pathname) { String name = pathname.getName().toLowerCase(); return !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj") && !name.endsWith(".lst") && !name.endsWith(".jar"); } }); - for (int i = 0; i < fromResources.length; i++) { - String normPath = FileUtil.normalizedPath(fromResources[i], srcBase[j]); - sourcePathResources.put(normPath, fromResources[i]); + for (File fromResource : fromResources) { + String normPath = FileUtil.normalizedPath(fromResource, file); + sourcePathResources.put(normPath, fromResource); } } diff --git a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/HtmlDecorator.java b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/HtmlDecorator.java index 7dd50b4ef..35e84ca5a 100644 --- a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/HtmlDecorator.java +++ b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/HtmlDecorator.java @@ -58,8 +58,8 @@ class HtmlDecorator { rootDir = newRootDir; declIDTable = table; docVisibilityModifier = docModifier; - for (int i = 0; i < inputFiles.length; i++) { - decorateHTMLFromIPEs(getProgramElements(model, inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath() + for (File inputFile : inputFiles) { + decorateHTMLFromIPEs(getProgramElements(model, inputFile.getCanonicalPath()), rootDir.getCanonicalPath() + Config.DIR_SEP_CHAR, docModifier, false); } } @@ -67,8 +67,7 @@ class HtmlDecorator { static void decorateHTMLFromIPEs(IProgramElement[] decls, String base, String docModifier, boolean exceededNestingLevel) throws IOException { if (decls != null) { - for (int i = 0; i < decls.length; i++) { - IProgramElement decl = decls[i]; + for (IProgramElement decl : decls) { decorateHTMLFromIPE(decl, base, docModifier, exceededNestingLevel); } } @@ -311,8 +310,7 @@ class HtmlDecorator { if (fieldsDeclaredOn != null && !constDeclaredOn.isEmpty()) { insertDeclarationsSummary(fileBuffer, constDeclaredOn, ITD_CONSTRUCTOR_SUMMARY, index); } - for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) { - IProgramElement member = it.next(); + for (IProgramElement member : node.getChildren()) { if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) { pointcuts.add(member); } else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) { @@ -365,8 +363,8 @@ class HtmlDecorator { insertIndex += tableHead.length(); // insert the body of the table - for (int i = 0; i < decls.size(); i++) { - IProgramElement decl = (IProgramElement) decls.get(i); + for (Object o : decls) { + IProgramElement decl = (IProgramElement) o; if (isAboveVisibility(decl)) { // insert the table row accordingly String comment = generateSummaryComment(decl); @@ -413,8 +411,8 @@ class HtmlDecorator { private static boolean declsAboveVisibilityExist(List decls) { boolean exist = false; - for (Iterator it = decls.iterator(); it.hasNext();) { - IProgramElement element = (IProgramElement) it.next(); + for (Object decl : decls) { + IProgramElement element = (IProgramElement) decl; if (isAboveVisibility(element)) exist = true; } @@ -810,11 +808,11 @@ class HtmlDecorator { static String generateHREFName(IProgramElement decl) { StringBuffer hrefLinkBuffer = new StringBuffer(); char[] declChars = decl.toLabelString().toCharArray(); - for (int i = 0; i < declChars.length; i++) { - if (declChars[i] == '"') { + for (char declChar : declChars) { + if (declChar == '"') { hrefLinkBuffer.append("quot;"); } else { - hrefLinkBuffer.append(declChars[i]); + hrefLinkBuffer.append(declChar); } } return hrefLinkBuffer.toString(); diff --git a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/Main.java b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/Main.java index e4cf8be44..0f01a058f 100644 --- a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/Main.java +++ b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/Main.java @@ -171,14 +171,14 @@ public class Main implements Config { */ private static void packageHTML(AsmManager model, File[] inputFiles) throws IOException { ArrayList<String> dirList = new ArrayList<String>(); - for (int i = 0; i < inputFiles.length; i++) { - String packageName = StructureUtil.getPackageDeclarationFromFile(model, inputFiles[i]); + for (File inputFile : inputFiles) { + String packageName = StructureUtil.getPackageDeclarationFromFile(model, inputFile); // Only copy the package.html file once. if (dirList.contains(packageName)) continue; // Check to see if there exist a package.html file for this package. - String dir = inputFiles[i].getAbsolutePath().substring(0, inputFiles[i].getAbsolutePath().lastIndexOf(File.separator)); + String dir = inputFile.getAbsolutePath().substring(0, inputFile.getAbsolutePath().lastIndexOf(File.separator)); File input = new File(dir + Config.DIR_SEP_CHAR + "package.html"); File inDir = new File(dir + Config.DIR_SEP_CHAR + "doc-files"); // If it does not exist lets go to the next package. @@ -226,8 +226,8 @@ public class Main implements Config { for (; i < ajcOptions.size(); i++) { argsToCompiler[i] = ajcOptions.elementAt(i); } - for (int j = 0; j < inputFiles.length; j++) { - argsToCompiler[i] = inputFiles[j].getAbsolutePath(); + for (File inputFile : inputFiles) { + argsToCompiler[i] = inputFile.getAbsolutePath(); // System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath()); i++; } @@ -281,8 +281,8 @@ public class Main implements Config { for (int k = 0; k < signatureFiles.length; k++) { javadocargs[options.size() + k] = StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath()); } - for (int k = 0; k < signatureFiles.length; k++) { - files.add(StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath())); + for (File signatureFile : signatureFiles) { + files.add(StructureUtil.translateAjPathName(signatureFile.getCanonicalPath())); } } if (LangUtil.is19VMOrGreater()) { @@ -321,8 +321,8 @@ public class Main implements Config { return f.getName().equals("package-summary.html"); } }); - for (int j = 0; j < files.length; j++) { - removeDeclIDsFromFile(files[j].getAbsolutePath(), false); + for (File file : files) { + removeDeclIDsFromFile(file.getAbsolutePath(), false); } } } @@ -478,8 +478,8 @@ public class Main implements Config { // System.err.println(argList); args = new String[argList.size()]; int counter = 0; - for (Iterator<String> it = argList.iterator(); it.hasNext();) { - args[counter] = it.next(); + for (String s : argList) { + args[counter] = s; counter++; } } catch (FileNotFoundException e) { @@ -530,8 +530,8 @@ public class Main implements Config { if (vargs.size() == 0) { displayHelpAndExit(null); } - for (int i = 0; i < vargs.size(); i++) { - String arg = (String) vargs.get(i); + for (Object varg : vargs) { + String arg = (String) varg; ignoreArg = false; if (addNextAsDocDir) { docDir = arg; @@ -694,16 +694,16 @@ public class Main implements Config { int index2 = name.length(); if ((index1 >= 0 && index2 >= 0) && (name.substring(index1, index2).equals(".java") || name.substring(index1, index2) - .equals(".aj"))) { + .equals(".aj"))) { return true; } else { return false; } } }); - for (int j = 0; j < files.length; j++) { + for (String file : files) { filenames.addElement(sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg - + Config.DIR_SEP_CHAR + files[j]); + + Config.DIR_SEP_CHAR + file); } } else if (c == sourcepath.size()) { // last element on classpath System.out.println("ajdoc: No package, class, or source file " + "found named " + arg + "."); diff --git a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StructureUtil.java b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StructureUtil.java index 3d866b625..2fdd95698 100644 --- a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StructureUtil.java +++ b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StructureUtil.java @@ -47,16 +47,14 @@ public class StructureUtil { if (rels != null) { relations.addAll(rels); } - for (Iterator<IProgramElement> iter = node.getChildren().iterator(); iter.hasNext();) { - IProgramElement child = (IProgramElement) iter.next(); + for (IProgramElement child : node.getChildren()) { // if we're not a type, or if we are and the child is code, then // we want to get the relationships for this child - this means that the // correct relationships appear against the type in the ajdoc if (!node.getKind().isType() || child.getKind().equals(IProgramElement.Kind.CODE)) { List<IRelationship> childRelations = node.getModel().getRelationshipMap().get(child); if (childRelations != null) { - for (Iterator<IRelationship> iterator = childRelations.iterator(); iterator.hasNext();) { - IRelationship rel = (IRelationship) iterator.next(); + for (IRelationship rel : childRelations) { if (!relations.contains(rel)) { relations.add(rel); } @@ -67,11 +65,10 @@ public class StructureUtil { if (relations == null || relations.isEmpty()) return null; List<String> targets = new ArrayList<String>(); - for (Iterator<IRelationship> it = relations.iterator(); it.hasNext();) { - IRelationship rtn = (IRelationship) it.next(); + for (IRelationship rtn : relations) { if (rtn.getKind().equals(kind) && ((relName != null && relName.equals(rtn.getName())) || relName == null)) { List<String> targs = rtn.getTargets(); - for (String element: targs) { + for (String element : targs) { if (!targets.contains(element)) { targets.add(element); } @@ -125,8 +122,8 @@ public class StructureUtil { } String modifiers = ""; - for (Iterator modIt = node.getModifiers().iterator(); modIt.hasNext();) { - modifiers += modIt.next() + " "; + for (IProgramElement.Modifiers value : node.getModifiers()) { + modifiers += value + " "; } if (node.getKind().equals(IProgramElement.Kind.METHOD) || node.getKind().equals(IProgramElement.Kind.FIELD)) { diff --git a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StubFileGenerator.java b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StubFileGenerator.java index 6b5c816f7..cd8a01e26 100644 --- a/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StubFileGenerator.java +++ b/ajdoc/src/main/java/org/aspectj/tools/ajdoc/StubFileGenerator.java @@ -59,8 +59,7 @@ class StubFileGenerator { } IProgramElement fileNode = model.getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath()); - for (Iterator it = fileNode.getChildren().iterator(); it.hasNext();) { - IProgramElement node = (IProgramElement) it.next(); + for (IProgramElement node : fileNode.getChildren()) { if (node.getKind().isPackageDeclaration()) { // skip } else if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) { @@ -84,8 +83,8 @@ class StubFileGenerator { private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException { List imports = node.getChildren(); - for (Iterator i = imports.iterator(); i.hasNext();) { - IProgramElement importNode = (IProgramElement) i.next(); + for (Object anImport : imports) { + IProgramElement importNode = (IProgramElement) anImport; writer.println(importNode.getSourceSignature()); } } @@ -111,8 +110,8 @@ class StubFileGenerator { private static void processMembers(List/* IProgramElement */members, PrintWriter writer, boolean declaringTypeIsInterface) throws DocException { - for (Iterator it = members.iterator(); it.hasNext();) { - IProgramElement member = (IProgramElement) it.next(); + for (Object o : members) { + IProgramElement member = (IProgramElement) o; if (member.getKind().isType()) { if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't diff --git a/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocOutputChecker.java b/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocOutputChecker.java index 2100f7dba..b22d1250d 100644 --- a/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocOutputChecker.java +++ b/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocOutputChecker.java @@ -61,8 +61,7 @@ public class AjdocOutputChecker { */ public static List<String> getMissingStringsInFile(File htmlFile, String[] requiredStrings) throws Exception { List<String> missingStrings = new ArrayList<String>(); - for (int i = 0; i < requiredStrings.length; i++) { - String string = requiredStrings[i]; + for (String string : requiredStrings) { if (!containsString(htmlFile, string)) { missingStrings.add(string); } @@ -122,9 +121,8 @@ public class AjdocOutputChecker { public static List<String> getMissingStringsInSection(File htmlFile, String[] requiredStrings, String sectionHeader) throws Exception { List<String> missingStrings = new ArrayList<String>(); - for (int i = 0; i < requiredStrings.length; i++) { - String string = requiredStrings[i]; - if (!containsStringWithinSection(htmlFile,string,sectionHeader)) { + for (String string : requiredStrings) { + if (!containsStringWithinSection(htmlFile, string, sectionHeader)) { missingStrings.add(string); } } diff --git a/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocTestCase.java b/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocTestCase.java index 26dda1187..6dfd5633f 100644 --- a/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocTestCase.java +++ b/ajdoc/src/test/java/org/aspectj/tools/ajdoc/AjdocTestCase.java @@ -97,8 +97,7 @@ public abstract class AjdocTestCase extends TestCase { String contents[] = from.list(); if (contents == null) return; - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(from, string); File t = new File(to, string); @@ -209,9 +208,9 @@ public abstract class AjdocTestCase extends TestCase { if (inputFiles.length == 0) { fail("need to pass some files into ajdoc"); } - for (int i = 0; i < inputFiles.length; i++) { - if (!inputFiles[i].exists()) { - fail(inputFiles[i].getAbsolutePath() + " does not exist"); + for (File inputFile : inputFiles) { + if (!inputFile.exists()) { + fail(inputFile.getAbsolutePath() + " does not exist"); } } @@ -305,8 +304,8 @@ public abstract class AjdocTestCase extends TestCase { public void runAjdoc(List options) { String[] args = new String[options.size()]; int i = 0; - for (Iterator iter = options.iterator(); iter.hasNext();) { - String element = (String) iter.next(); + for (Object option : options) { + String element = (String) option; args[i] = element; i++; } diff --git a/asm/src/main/java/org/aspectj/asm/AsmManager.java b/asm/src/main/java/org/aspectj/asm/AsmManager.java index 2ab34c862..6972dda3a 100644 --- a/asm/src/main/java/org/aspectj/asm/AsmManager.java +++ b/asm/src/main/java/org/aspectj/asm/AsmManager.java @@ -157,8 +157,7 @@ public class AsmManager implements IStructureModel { IProgramElement fileNode = node; ArrayList<IProgramElement> peNodes = new ArrayList<IProgramElement>(); getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType); - for (Iterator<IProgramElement> it = peNodes.iterator(); it.hasNext();) { - IProgramElement peNode = it.next(); + for (IProgramElement peNode : peNodes) { List<IProgramElement> entries = new ArrayList<IProgramElement>(); entries.add(peNode); ISourceLocation sourceLoc = peNode.getSourceLocation(); @@ -733,8 +732,8 @@ public class AsmManager implements IStructureModel { if (relationshipsToRemove.size() == relationships.size()) { sourcesToRemove.add(hid); } else { - for (int i = 0; i < relationshipsToRemove.size(); i++) { - relationships.remove(relationshipsToRemove.get(i)); + for (IRelationship iRelationship : relationshipsToRemove) { + relationships.remove(iRelationship); } } } @@ -815,8 +814,8 @@ public class AsmManager implements IStructureModel { if (relationshipsToRemove.size() == relationships.size()) { sourcesToRemove.add(hid); } else { - for (int i = 0; i < relationshipsToRemove.size(); i++) { - relationships.remove(relationshipsToRemove.get(i)); + for (IRelationship iRelationship : relationshipsToRemove) { + relationships.remove(iRelationship); } } } @@ -960,15 +959,13 @@ public class AsmManager implements IStructureModel { List<IRelationship> relationshipsToRemove = new ArrayList<IRelationship>(); // Iterate through the relationships against this source // handle - for (Iterator<IRelationship> reliter = relationships.iterator(); reliter.hasNext();) { - IRelationship rel = reliter.next(); + for (IRelationship rel : relationships) { List<String> targets = rel.getTargets(); List<String> targetsToRemove = new ArrayList<String>(); // Iterate through the targets for this relationship - for (Iterator<String> targetIter = targets.iterator(); targetIter.hasNext();) { - String targethid = targetIter.next(); -// tgthandlecounter++; + for (String targethid : targets) { + // tgthandlecounter++; // Do we already know it doesn't exist? if (nonExistingHandles.contains(targethid)) { if (dumpDeltaProcessing) { @@ -1040,8 +1037,7 @@ public class AsmManager implements IStructureModel { } else { // MEMORY LEAK - we don't remove the // relationships !! - for (int i = 0; i < relationshipsToRemove.size(); i++) { - IRelationship irel = relationshipsToRemove.get(i); + for (IRelationship irel : relationshipsToRemove) { verifyAssumption(mapper.remove(hid, irel), "Failed to remove relationship " + irel.getName() + " for shid " + hid); } @@ -1055,8 +1051,7 @@ public class AsmManager implements IStructureModel { } } // Remove sources that have no valid relationships any more - for (Iterator<String> srciter = sourcesToRemove.iterator(); srciter.hasNext();) { - String hid = srciter.next(); + for (String hid : sourcesToRemove) { mapper.removeAll(hid); IProgramElement ipe = hierarchy.getElement(hid); if (ipe != null) { diff --git a/asm/src/main/java/org/aspectj/asm/IProgramElement.java b/asm/src/main/java/org/aspectj/asm/IProgramElement.java index 19e6d95ac..402376217 100644 --- a/asm/src/main/java/org/aspectj/asm/IProgramElement.java +++ b/asm/src/main/java/org/aspectj/asm/IProgramElement.java @@ -330,11 +330,11 @@ public interface IProgramElement extends Serializable { }; public static Kind getKindForString(String kindString) { - for (int i = 0; i < ALL.length; i++) { - if (ALL[i].toString().equals(kindString)) { - return ALL[i]; - } - } + for (Kind kind : ALL) { + if (kind.toString().equals(kindString)) { + return kind; + } + } return ERROR; } diff --git a/asm/src/main/java/org/aspectj/asm/IRelationship.java b/asm/src/main/java/org/aspectj/asm/IRelationship.java index 86633cf36..441a3d2d0 100644 --- a/asm/src/main/java/org/aspectj/asm/IRelationship.java +++ b/asm/src/main/java/org/aspectj/asm/IRelationship.java @@ -75,9 +75,9 @@ public interface IRelationship extends Serializable { * @return the Kind instance */ public static Kind getKindFor(String stringFormOfRelationshipKind) { - for (int i = 0; i < ALL.length; i++) { - if (ALL[i].name.equals(stringFormOfRelationshipKind)) { - return ALL[i]; + for (Kind kind : ALL) { + if (kind.name.equals(stringFormOfRelationshipKind)) { + return kind; } } return null; diff --git a/asm/src/main/java/org/aspectj/asm/internal/JDTLikeHandleProvider.java b/asm/src/main/java/org/aspectj/asm/internal/JDTLikeHandleProvider.java index 3751dfc1b..15eb990ee 100644 --- a/asm/src/main/java/org/aspectj/asm/internal/JDTLikeHandleProvider.java +++ b/asm/src/main/java/org/aspectj/asm/internal/JDTLikeHandleProvider.java @@ -136,8 +136,7 @@ public class JDTLikeHandleProvider implements IElementHandleProvider { List<char[]> parameterTypes = ipe.getParameterSignatures(); StringBuffer sb = new StringBuffer(); if (sourceRefs != null) { - for (int i = 0; i < sourceRefs.size(); i++) { - String sourceRef = sourceRefs.get(i); + for (String sourceRef : sourceRefs) { sb.append(HandleProviderDelimiter.getDelimiter(ipe)); sb.append(sourceRef); } @@ -164,8 +163,7 @@ public class JDTLikeHandleProvider implements IElementHandleProvider { if (ipe.getKind().isInterTypeMember()) { int count = 1; List<IProgramElement> kids = ipe.getParent().getChildren(); - for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) { - IProgramElement object = iterator.next(); + for (IProgramElement object : kids) { if (object.equals(ipe)) { break; } diff --git a/asm/src/main/java/org/aspectj/asm/internal/ProgramElement.java b/asm/src/main/java/org/aspectj/asm/internal/ProgramElement.java index 51aafd936..c1479f70f 100644 --- a/asm/src/main/java/org/aspectj/asm/internal/ProgramElement.java +++ b/asm/src/main/java/org/aspectj/asm/internal/ProgramElement.java @@ -544,8 +544,8 @@ public class ProgramElement implements IProgramElement { if (children == null) { return; } - for (Iterator<IProgramElement> it = children.iterator(); it.hasNext();) { - (it.next()).setParent(this); + for (IProgramElement child : children) { + child.setParent(this); } } @@ -751,8 +751,7 @@ public class ProgramElement implements IProgramElement { return Collections.emptyList(); } List<char[]> params = new ArrayList<char[]>(); - for (Iterator<char[]> iter = l.iterator(); iter.hasNext();) { - char[] param = iter.next(); + for (char[] param : l) { params.add(NameConvertor.convertFromSignature(param)); } return params; diff --git a/asm/src/main/java/org/aspectj/asm/internal/RelationshipMap.java b/asm/src/main/java/org/aspectj/asm/internal/RelationshipMap.java index 1fea7bb85..0df2fdd89 100644 --- a/asm/src/main/java/org/aspectj/asm/internal/RelationshipMap.java +++ b/asm/src/main/java/org/aspectj/asm/internal/RelationshipMap.java @@ -62,8 +62,7 @@ public class RelationshipMap extends HashMap<String, List<IRelationship>> implem super.put(source, relationships); return rel; } else { - for (Iterator<IRelationship> it = relationships.iterator(); it.hasNext();) { - IRelationship curr = it.next(); + for (IRelationship curr : relationships) { if (curr.getKind() == kind && curr.getName().equals(relationshipName) && curr.hasRuntimeTest() == runtimeTest) { return curr; } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java index 45d1597a7..d28a4f9f4 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/AttributeUtils.java @@ -30,57 +30,57 @@ public class AttributeUtils { file.writeShort(0); } else { file.writeShort(attributes.length); - for (int i = 0; i < attributes.length; i++) { - attributes[i].dump(file); + for (Attribute attribute : attributes) { + attribute.dump(file); } } } public static Signature getSignatureAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_SIGNATURE) { - return (Signature) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_SIGNATURE) { + return (Signature) attribute; } } return null; } public static Code getCodeAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_CODE) { - return (Code) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_CODE) { + return (Code) attribute; } } return null; } public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) { - return (ExceptionTable) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_EXCEPTIONS) { + return (ExceptionTable) attribute; } } return null; } public static ConstantValue getConstantValueAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) { - return (ConstantValue) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.getTag() == Constants.ATTR_CONSTANT_VALUE) { + return (ConstantValue) attribute; } } return null; } public static void accept(Attribute[] attributes, ClassVisitor visitor) { - for (int i = 0; i < attributes.length; i++) { - attributes[i].accept(visitor); + for (Attribute attribute : attributes) { + attribute.accept(visitor); } } public static boolean hasSyntheticAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_SYNTHETIC) { + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_SYNTHETIC) { return true; } } @@ -88,9 +88,9 @@ public class AttributeUtils { } public static SourceFile getSourceFileAttribute(Attribute[] attributes) { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) { - return (SourceFile) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_SOURCE_FILE) { + return (SourceFile) attribute; } } return null; diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/BootstrapMethods.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/BootstrapMethods.java index f708c0cab..699cdc3ef 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/BootstrapMethods.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/BootstrapMethods.java @@ -133,8 +133,8 @@ public final class BootstrapMethods extends Attribute { file.writeShort(bootstrapMethodRef); int len = bootstrapArguments.length; file.writeShort(len); - for (int i=0;i<len;i++) { - file.writeShort(bootstrapArguments[i]); + for (int bootstrapArgument : bootstrapArguments) { + file.writeShort(bootstrapArgument); } } @@ -192,8 +192,8 @@ public final class BootstrapMethods extends Attribute { } else { int blen = bootstrapMethods.length; file.writeShort(blen); - for (int i = 0; i < blen; i++) { - bootstrapMethods[i].dump(file); + for (BootstrapMethod bootstrapMethod : bootstrapMethods) { + bootstrapMethod.dump(file); } } } @@ -224,8 +224,8 @@ public final class BootstrapMethods extends Attribute { int [] args = bm.getBootstrapArguments(); line.append(" argcount:").append(args==null?0:args.length).append(" "); if (args!=null) { - for (int a=0;a<args.length;a++) { - line.append(args[a]).append("(").append(getConstantPool().getConstant(args[a])).append(") "); + for (int arg : args) { + line.append(arg).append("(").append(getConstantPool().getConstant(arg)).append(") "); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Code.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Code.java index b714e6cab..10dbf8ffc 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Code.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Code.java @@ -173,13 +173,13 @@ public final class Code extends Attribute { file.write(code, 0, code.length); file.writeShort(exceptionTable.length); - for (int i = 0; i < exceptionTable.length; i++) { - exceptionTable[i].dump(file); + for (CodeException e : exceptionTable) { + e.dump(file); } file.writeShort(attributes.length); - for (int i = 0; i < attributes.length; i++) { - attributes[i].dump(file); + for (Attribute attribute : attributes) { + attribute.dump(file); } } @@ -195,9 +195,9 @@ public final class Code extends Attribute { * @return LineNumberTable of Code, if it has one */ public LineNumberTable getLineNumberTable() { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_LINE_NUMBER_TABLE) { - return (LineNumberTable) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_LINE_NUMBER_TABLE) { + return (LineNumberTable) attribute; } } return null; @@ -207,9 +207,9 @@ public final class Code extends Attribute { * @return LocalVariableTable of Code, if it has one */ public LocalVariableTable getLocalVariableTable() { - for (int i = 0; i < attributes.length; i++) { - if (attributes[i].tag == Constants.ATTR_LOCAL_VARIABLE_TABLE) { - return (LocalVariableTable) attributes[i]; + for (Attribute attribute : attributes) { + if (attribute.tag == Constants.ATTR_LOCAL_VARIABLE_TABLE) { + return (LocalVariableTable) attribute; } } return null; @@ -262,8 +262,8 @@ public final class Code extends Attribute { private final int calculateLength() { int len = 0; if (attributes != null) { - for (int i = 0; i < attributes.length; i++) { - len += attributes[i].length + 6 /* attribute header size */; + for (Attribute attribute : attributes) { + len += attribute.length + 6 /* attribute header size */; } } return len + getInternalLength(); @@ -317,16 +317,16 @@ public final class Code extends Attribute { if (exceptionTable.length > 0) { buf.append("\nException handler(s) = \n" + "From\tTo\tHandler\tType\n"); - for (int i = 0; i < exceptionTable.length; i++) { - buf.append(exceptionTable[i].toString(cpool, verbose) + "\n"); + for (CodeException e : exceptionTable) { + buf.append(e.toString(cpool, verbose) + "\n"); } } if (attributes.length > 0) { buf.append("\nAttribute(s) = \n"); - for (int i = 0; i < attributes.length; i++) { - buf.append(attributes[i].toString() + "\n"); + for (Attribute attribute : attributes) { + buf.append(attribute.toString() + "\n"); } } @@ -372,8 +372,7 @@ public final class Code extends Attribute { codeString.append(Utility.codeToString(code, cpool, 0, -1, true)); if (exceptionTable.length > 0) { codeString.append("\n").append("Exception entries = ").append(exceptionTable.length).append("\n"); - for (int i = 0; i < exceptionTable.length; i++) { - CodeException exc = exceptionTable[i]; + for (CodeException exc : exceptionTable) { int type = exc.getCatchType(); String name = "finally"; if (type != 0) { diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/FieldOrMethod.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/FieldOrMethod.java index a152b616f..8689e31b9 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/FieldOrMethod.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/FieldOrMethod.java @@ -168,8 +168,7 @@ public abstract class FieldOrMethod extends Modifiers implements Node { if (annotations == null) { // Find attributes that contain annotation data List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>(); - for (int i = 0; i < attributes.length; i++) { - Attribute attribute = attributes[i]; + for (Attribute attribute : attributes) { if (attribute instanceof RuntimeAnnos) { RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attribute; accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations()); diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java index 25c415295..59c092239 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/JavaClass.java @@ -260,18 +260,18 @@ public class JavaClass extends Modifiers implements Cloneable, Node { file.writeShort(superclassnameIdx); file.writeShort(interfaces.length); - for (int i = 0; i < interfaces.length; i++) { - file.writeShort(interfaces[i]); + for (int anInterface : interfaces) { + file.writeShort(anInterface); } file.writeShort(fields.length); - for (int i = 0; i < fields.length; i++) { - fields[i].dump(file); + for (Field field : fields) { + field.dump(file); } file.writeShort(methods.length); - for (int i = 0; i < methods.length; i++) { - methods[i].dump(file); + for (Method method : methods) { + method.dump(file); } AttributeUtils.writeAttributes(attributes, file); @@ -287,8 +287,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { if (annotationsOutOfDate) { // Find attributes that contain annotation data List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>(); - for (int i = 0; i < attributes.length; i++) { - Attribute attribute = attributes[i]; + for (Attribute attribute : attributes) { if (attribute instanceof RuntimeAnnos) { RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attribute; accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations()); @@ -366,9 +365,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { * @return A org.aspectj.apache.bcel.classfile.Method corresponding to java.lang.reflect.Method if any */ public Method getMethod(java.lang.reflect.Method m) { - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; - + for (Method method : methods) { if (m.getName().equals(method.getName()) && m.getModifiers() == method.getModifiers() && Type.getSignature(m).equals(method.getSignature())) { return method; @@ -379,8 +376,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { } public Method getMethod(java.lang.reflect.Constructor<?> c) { - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { if (method.getName().equals("<init>") && c.getModifiers() == method.getModifiers() && Type.getSignature(c).equals(method.getSignature())) { return method; @@ -552,29 +548,29 @@ public class JavaClass extends Modifiers implements Cloneable, Node { if (attributes.length > 0) { buf.append("\nAttribute(s):\n"); - for (int i = 0; i < attributes.length; i++) { - buf.append(indent(attributes[i])); + for (Attribute attribute : attributes) { + buf.append(indent(attribute)); } } if (annotations != null && annotations.length > 0) { buf.append("\nAnnotation(s):\n"); - for (int i = 0; i < annotations.length; i++) { - buf.append(indent(annotations[i])); + for (AnnotationGen annotation : annotations) { + buf.append(indent(annotation)); } } if (fields.length > 0) { buf.append("\n" + fields.length + " fields:\n"); - for (int i = 0; i < fields.length; i++) { - buf.append("\t" + fields[i] + '\n'); + for (Field field : fields) { + buf.append("\t" + field + '\n'); } } if (methods.length > 0) { buf.append("\n" + methods.length + " methods:\n"); - for (int i = 0; i < methods.length; i++) { - buf.append("\t" + methods[i] + '\n'); + for (Method method : methods) { + buf.append("\t" + method + '\n'); } } @@ -615,12 +611,12 @@ public class JavaClass extends Modifiers implements Cloneable, Node { return; } // Attribute[] attrs = attributes.getAttributes(); - for (int i = 0; i < attributes.length; i++) { - if (attributes[i] instanceof InnerClasses) { - InnerClass[] innerClasses = ((InnerClasses) attributes[i]).getInnerClasses(); - for (int j = 0; j < innerClasses.length; j++) { + for (Attribute attribute : attributes) { + if (attribute instanceof InnerClasses) { + InnerClass[] innerClasses = ((InnerClasses) attribute).getInnerClasses(); + for (InnerClass innerClass : innerClasses) { boolean innerClassAttributeRefersToMe = false; - String inner_class_name = cpool.getConstantString(innerClasses[j].getInnerClassIndex(), + String inner_class_name = cpool.getConstantString(innerClass.getInnerClassIndex(), Constants.CONSTANT_Class); inner_class_name = Utility.compactClassName(inner_class_name); if (inner_class_name.equals(getClassName())) { @@ -628,7 +624,7 @@ public class JavaClass extends Modifiers implements Cloneable, Node { } if (innerClassAttributeRefersToMe) { this.isNested = true; - if (innerClasses[j].getInnerNameIndex() == 0) { + if (innerClass.getInnerNameIndex() == 0) { this.isAnonymous = true; } } @@ -684,8 +680,8 @@ public class JavaClass extends Modifiers implements Cloneable, Node { JavaClass[] super_classes = getSuperClasses(); - for (int i = 0; i < super_classes.length; i++) { - if (super_classes[i].equals(super_class)) { + for (JavaClass superClass : super_classes) { + if (superClass.equals(super_class)) { return true; } } @@ -795,8 +791,8 @@ public class JavaClass extends Modifiers implements Cloneable, Node { } } - for (int i = 0; i < interfaces.length; i++) { - queue.add(interfaces[i]); + for (JavaClass anInterface : interfaces) { + queue.add(anInterface); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Method.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Method.java index 46aeac845..baa0629c6 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Method.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Method.java @@ -165,11 +165,10 @@ public final class Method extends FieldOrMethod { signature = Utility.methodSignatureToString(signature, name, access, true, getLocalVariableTable()); buf = new StringBuffer(signature); - for (int i = 0; i < attributes.length; i++) { - Attribute a = attributes[i]; - if (!((a instanceof Code) || (a instanceof ExceptionTable))) - buf.append(" [" + a.toString() + "]"); - } + for (Attribute a : attributes) { + if (!((a instanceof Code) || (a instanceof ExceptionTable))) + buf.append(" [" + a.toString() + "]"); + } ExceptionTable e = getExceptionTable(); if (e != null) { @@ -212,14 +211,14 @@ public final class Method extends FieldOrMethod { // Find attributes that contain annotation data Attribute[] attrs = getAttributes(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; - if (attribute instanceof RuntimeVisParamAnnos) { - parameterAnnotationsVis = (RuntimeVisParamAnnos) attribute; - } else if (attribute instanceof RuntimeInvisParamAnnos) { - parameterAnnotationsInvis = (RuntimeInvisParamAnnos) attribute; - } - } + for (Attribute attribute : attrs) { + if (attribute instanceof RuntimeVisParamAnnos) { + parameterAnnotationsVis = (RuntimeVisParamAnnos) attribute; + } + else if (attribute instanceof RuntimeInvisParamAnnos) { + parameterAnnotationsInvis = (RuntimeInvisParamAnnos) attribute; + } + } boolean foundSome = false; // Build a list of annotation arrays, one per argument diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java index 5eef18cde..1302aeede 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Module.java @@ -438,10 +438,10 @@ public final class Module extends Attribute { file.writeShort(moduleVersionIndex); file.writeShort(requires.length); - for (int i = 0; i < requires.length; i++) { - file.writeShort(requires[i].moduleIndex); - file.writeShort(requires[i].flags); - file.writeShort(requires[i].versionIndex); + for (Require require : requires) { + file.writeShort(require.moduleIndex); + file.writeShort(require.flags); + file.writeShort(require.versionIndex); } file.writeShort(exports.length); for (Export export : exports) { diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/ModulePackages.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/ModulePackages.java index 37da4bc47..6f96ae0fd 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/ModulePackages.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/ModulePackages.java @@ -97,8 +97,8 @@ public final class ModulePackages extends Attribute { public final void dump(DataOutputStream stream) throws IOException { super.dump(stream); stream.writeShort(packageIndices.length); - for (int i = 0; i < packageIndices.length; i++) { - stream.writeShort(packageIndices[i]); + for (int packageIndex : packageIndices) { + stream.writeShort(packageIndex); } } @@ -117,8 +117,8 @@ public final class ModulePackages extends Attribute { @Override public final String toString() { StringBuffer buf = new StringBuffer(); - for (int i = 0; i < packageIndices.length; i++) { - buf.append(cpool.getPackageName(packageIndices[i]) + "\n"); + for (int packageIndex : packageIndices) { + buf.append(cpool.getPackageName(packageIndex) + "\n"); } return buf.toString(); } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Utility.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Utility.java index 98f5952ae..2d4b2a81f 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Utility.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/Utility.java @@ -522,26 +522,26 @@ public abstract class Utility { char[] ch = label.toCharArray(); StringBuffer buf = new StringBuffer(); - for (int i = 0; i < ch.length; i++) { - switch (ch[i]) { - case '\n': - buf.append("\\n"); - break; - case '\r': - buf.append("\\r"); - break; - case '\"': - buf.append("\\\""); - break; - case '\'': - buf.append("\\'"); - break; - case '\\': - buf.append("\\\\"); - break; - default: - buf.append(ch[i]); - break; + for (char c : ch) { + switch (c) { + case '\n': + buf.append("\\n"); + break; + case '\r': + buf.append("\\r"); + break; + case '\"': + buf.append("\\\""); + break; + case '\'': + buf.append("\\'"); + break; + case '\\': + buf.append("\\\\"); + break; + default: + buf.append(c); + break; } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java index 9a0a42909..8074e383e 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/AnnotationGen.java @@ -82,8 +82,7 @@ public class AnnotationGen { public void dump(DataOutputStream dos) throws IOException { dos.writeShort(typeIndex); // u2 index of type name in cpool dos.writeShort(pairs.size()); // u2 element_value pair count - for (int i = 0; i < pairs.size(); i++) { - NameValuePair envp = pairs.get(i); + for (NameValuePair envp : pairs) { envp.dump(dos); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/ArrayElementValue.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/ArrayElementValue.java index 3dd19af71..4cb5f5fe8 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/ArrayElementValue.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/ArrayElementValue.java @@ -55,8 +55,8 @@ public class ArrayElementValue extends ElementValue { public void dump(DataOutputStream dos) throws IOException { dos.writeByte(type); // u1 type of value (ARRAY == '[') dos.writeShort(evalues.length); - for (int i = 0; i < evalues.length; i++) { - evalues[i].dump(dos); + for (ElementValue evalue : evalues) { + evalue.dump(dos); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeAnnos.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeAnnos.java index ac145087b..ecb1d539d 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeAnnos.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeAnnos.java @@ -64,8 +64,7 @@ public abstract class RuntimeAnnos extends Attribute { dos.write(annotation_data, 0, length); } else { dos.writeShort(annotations.size()); - for (Iterator<AnnotationGen> i = annotations.iterator(); i.hasNext();) { - AnnotationGen ann = i.next(); + for (AnnotationGen ann : annotations) { ann.dump(dos); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeParamAnnos.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeParamAnnos.java index 517ebee62..42bf903a1 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeParamAnnos.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeParamAnnos.java @@ -115,11 +115,10 @@ public abstract class RuntimeParamAnnos extends Attribute { dos.write(annotation_data,0,length); } else { dos.writeByte(parameterAnnotations.size()); - for (int i=0; i<parameterAnnotations.size(); i++) { - AnnotationGen[] annotations = parameterAnnotations.get(i); + for (AnnotationGen[] annotations : parameterAnnotations) { dos.writeShort(annotations.length); - for (int j=0; j<annotations.length;j++) { - annotations[j].dump(dos); + for (AnnotationGen annotation : annotations) { + annotation.dump(dos); } } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeTypeAnnos.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeTypeAnnos.java index fb5c32ce1..4e4fae650 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeTypeAnnos.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/RuntimeTypeAnnos.java @@ -47,8 +47,8 @@ public abstract class RuntimeTypeAnnos extends Attribute { dos.write(annotation_data,0,length); } else { dos.writeShort(typeAnnotations.length); - for (int i=0; i<typeAnnotations.length; i++) { - typeAnnotations[i].dump(dos); + for (TypeAnnotationGen typeAnnotation : typeAnnotations) { + typeAnnotation.dump(dos); } } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/TypeAnnotationGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/TypeAnnotationGen.java index 45e5928a3..ad7544eba 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/TypeAnnotationGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/classfile/annotation/TypeAnnotationGen.java @@ -182,8 +182,8 @@ public class TypeAnnotationGen { case LOCAL_VARIABLE: case RESOURCE_VARIABLE: dos.writeShort(localVarTarget.length/3); - for (int i=0;i<localVarTarget.length;i++) { - dos.writeShort(localVarTarget[i]); + for (int j : localVarTarget) { + dos.writeShort(j); } break; case EXCEPTION_PARAMETER: @@ -208,8 +208,8 @@ public class TypeAnnotationGen { throw new IllegalStateException("nyi "+targetType); } dos.writeByte(typePath.length); - for (int i=0;i<typePath.length;i++) { - dos.writeByte(typePath[i]); + for (int j : typePath) { + dos.writeByte(j); } annotation.dump(dos); } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java index 4ba767d97..8b7f0dd3f 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ClassGen.java @@ -141,8 +141,8 @@ public class ClassGen extends Modifiers implements Cloneable { Field[] fields = clazz.getFields(); String[] interfaces = clazz.getInterfaceNames(); - for (int i = 0; i < interfaces.length; i++) { - addInterface(interfaces[i]); + for (String anInterface : interfaces) { + addInterface(anInterface); } // OPTIMIZE Could make unpacking lazy, done on first reference @@ -165,12 +165,12 @@ public class ClassGen extends Modifiers implements Cloneable { } } - for (int i = 0; i < methods.length; i++) { - addMethod(methods[i]); + for (Method method : methods) { + addMethod(method); } - for (int i = 0; i < fields.length; i++) { - addField(fields[i]); + for (Field field : fields) { + addField(field); } } @@ -367,14 +367,12 @@ public class ClassGen extends Modifiers implements Cloneable { public void setMethods(Method[] methods) { methodsList.clear(); - for (int m = 0; m < methods.length; m++) - addMethod(methods[m]); + for (Method method : methods) addMethod(method); } public void setFields(Field[] fs) { fieldsList.clear(); - for (int m = 0; m < fs.length; m++) - addField(fs[m]); + for (Field f : fs) addField(f); } public void setMethodAt(Method method, int pos) { @@ -498,8 +496,7 @@ public class ClassGen extends Modifiers implements Cloneable { String[] names = getInterfaceNames(); if (names != null) { Arrays.sort(names); - for (int i = 0; i < names.length; i++) - dos.writeUTF(names[i]); + for (String name : names) dos.writeUTF(name); } // 4. ordered list of fields (ignoring private static and private transient fields): diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/FieldGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/FieldGen.java index 6a12a8c80..50b9ac496 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/FieldGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/FieldGen.java @@ -111,18 +111,17 @@ public class FieldGen extends FieldGenOrMethodGen { Attribute[] attrs = field.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - if (attrs[i] instanceof ConstantValue) { - setValue(((ConstantValue) attrs[i]).getConstantValueIndex()); - } else if (attrs[i] instanceof RuntimeAnnos) { - RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attrs[i]; + for (Attribute attr : attrs) { + if (attr instanceof ConstantValue) { + setValue(((ConstantValue) attr).getConstantValueIndex()); + } else if (attr instanceof RuntimeAnnos) { + RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attr; List<AnnotationGen> l = runtimeAnnotations.getAnnotations(); - for (Iterator<AnnotationGen> it = l.iterator(); it.hasNext();) { - AnnotationGen element = it.next(); + for (AnnotationGen element : l) { addAnnotation(new AnnotationGen(element, cp, false)); } } else { - addAttribute(attrs[i]); + addAttribute(attr); } } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionFactory.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionFactory.java index 4e1e6c8a8..a3b1fb30e 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionFactory.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionFactory.java @@ -119,8 +119,8 @@ public class InstructionFactory implements InstructionConstants { return new InvokeInstruction(Constants.INVOKESTATIC, index); case Constants.INVOKEINTERFACE: int nargs = 0; - for (int i = 0; i < arg_types.length; i++) { - nargs += arg_types[i].getSize(); + for (Type arg_type : arg_types) { + nargs += arg_type.getSize(); } return new INVOKEINTERFACE(index, nargs + 1, 0); default: @@ -148,8 +148,8 @@ public class InstructionFactory implements InstructionConstants { case Constants.INVOKEINTERFACE: Type[] argumentTypes = Type.getArgumentTypes(signature); int nargs = 0; - for (int i = 0; i < argumentTypes.length; i++) {// Count size of arguments - nargs += argumentTypes[i].getSize(); + for (Type argumentType : argumentTypes) {// Count size of arguments + nargs += argumentType.getSize(); } return new INVOKEINTERFACE(index, nargs + 1, 0); default: diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionList.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionList.java index b08a2b77c..dbdfb7fdb 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionList.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionList.java @@ -953,8 +953,8 @@ public class InstructionList implements Serializable { if (i instanceof InstructionSelect) { InstructionHandle[] targets = ((InstructionSelect) i).getTargets(); - for (int j = 0; j < targets.length; j++) { - inst = targets[j].instruction; + for (InstructionHandle target : targets) { + inst = target.instruction; if (!contains(inst)) { throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst + " not in instruction list"); @@ -1247,15 +1247,15 @@ public class InstructionList implements Serializable { * @see MethodGen */ public void redirectLocalVariables(LocalVariableGen[] lg, InstructionHandle old_target, InstructionHandle new_target) { - for (int i = 0; i < lg.length; i++) { - InstructionHandle start = lg[i].getStart(); - InstructionHandle end = lg[i].getEnd(); + for (LocalVariableGen localVariableGen : lg) { + InstructionHandle start = localVariableGen.getStart(); + InstructionHandle end = localVariableGen.getEnd(); if (start == old_target) { - lg[i].setStart(new_target); + localVariableGen.setStart(new_target); } if (end == old_target) { - lg[i].setEnd(new_target); + localVariableGen.setEnd(new_target); } } } @@ -1269,17 +1269,17 @@ public class InstructionList implements Serializable { * @see MethodGen */ public void redirectExceptionHandlers(CodeExceptionGen[] exceptions, InstructionHandle old_target, InstructionHandle new_target) { - for (int i = 0; i < exceptions.length; i++) { - if (exceptions[i].getStartPC() == old_target) { - exceptions[i].setStartPC(new_target); + for (CodeExceptionGen exception : exceptions) { + if (exception.getStartPC() == old_target) { + exception.setStartPC(new_target); } - if (exceptions[i].getEndPC() == old_target) { - exceptions[i].setEndPC(new_target); + if (exception.getEndPC() == old_target) { + exception.setEndPC(new_target); } - if (exceptions[i].getHandlerPC() == old_target) { - exceptions[i].setHandlerPC(new_target); + if (exception.getHandlerPC() == old_target) { + exception.setHandlerPC(new_target); } } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionSelect.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionSelect.java index b4e00c027..408f801ff 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionSelect.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/InstructionSelect.java @@ -88,8 +88,8 @@ public abstract class InstructionSelect extends InstructionBranch { super(opcode, target); this.targets = targets; - for (int i = 0; i < targets.length; i++) { - notifyTarget(null, targets[i], this); + for (InstructionHandle instructionHandle : targets) { + notifyTarget(null, instructionHandle, this); } this.match = match; @@ -236,8 +236,8 @@ public abstract class InstructionSelect extends InstructionBranch { return true; } - for (int i = 0; i < targets.length; i++) { - if (targets[i] == ih) { + for (InstructionHandle target : targets) { + if (target == ih) { return true; } } @@ -251,8 +251,8 @@ public abstract class InstructionSelect extends InstructionBranch { void dispose() { super.dispose(); - for (int i = 0; i < targets.length; i++) { - targets[i].removeTargeter(this); + for (InstructionHandle target : targets) { + target.removeTargeter(this); } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/MethodGen.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/MethodGen.java index 3938beb35..46b558146 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/MethodGen.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/MethodGen.java @@ -212,8 +212,8 @@ public class MethodGen extends FieldGenOrMethodGen { .getCode()) : null, cp); Attribute[] attributes = m.getAttributes(); - for (int i = 0; i < attributes.length; i++) { - Attribute a = attributes[i]; + for (Attribute attribute : attributes) { + Attribute a = attribute; if (a instanceof Code) { Code code = (Code) a; @@ -254,15 +254,14 @@ public class MethodGen extends FieldGenOrMethodGen { } Attribute[] codeAttrs = code.getAttributes(); - for (int j = 0; j < codeAttrs.length; j++) { - a = codeAttrs[j]; + for (Attribute codeAttr : codeAttrs) { + a = codeAttr; if (a instanceof LineNumberTable) { LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable(); if (useTags) { // abracadabra, lets create tags rather than linenumbergens. - for (int k = 0; k < ln.length; k++) { - LineNumber l = ln[k]; + for (LineNumber l : ln) { int lnum = l.getLineNumber(); if (lnum > highestLineNumber) { highestLineNumber = lnum; @@ -271,8 +270,7 @@ public class MethodGen extends FieldGenOrMethodGen { il.findHandle(l.getStartPC(), arrayOfInstructions, true).addTargeter(lt); } } else { - for (int k = 0; k < ln.length; k++) { - LineNumber l = ln[k]; + for (LineNumber l : ln) { addLineNumber(il.findHandle(l.getStartPC(), arrayOfInstructions, true), l.getLineNumber()); } } @@ -282,8 +280,7 @@ public class MethodGen extends FieldGenOrMethodGen { if (useTags) { LocalVariable[] lv = ((LocalVariableTable) a).getLocalVariableTable(); - for (int k = 0; k < lv.length; k++) { - LocalVariable l = lv[k]; + for (LocalVariable l : lv) { Type t = Type.getType(l.getSignature()); LocalVariableTag lvt = new LocalVariableTag(t, l.getSignature(), l.getName(), l.getIndex(), l .getStartPC()); @@ -307,8 +304,7 @@ public class MethodGen extends FieldGenOrMethodGen { removeLocalVariables(); - for (int k = 0; k < lv.length; k++) { - LocalVariable l = lv[k]; + for (LocalVariable l : lv) { InstructionHandle start = il.findHandle(l.getStartPC(), arrayOfInstructions); InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength(), arrayOfInstructions); // AMC, this actually gives us the first instruction AFTER the range, @@ -333,8 +329,8 @@ public class MethodGen extends FieldGenOrMethodGen { } } else if (a instanceof ExceptionTable) { String[] names = ((ExceptionTable) a).getExceptionNames(); - for (int j = 0; j < names.length; j++) { - addException(names[j]); + for (String s : names) { + addException(s); } } else if (a instanceof RuntimeAnnos) { RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) a; @@ -647,8 +643,8 @@ public class MethodGen extends FieldGenOrMethodGen { } Attribute[] attrs = Utility.getParameterAnnotationAttributes(cp, param_annotations); if (attrs != null) { - for (int i = 0; i < attrs.length; i++) { - addAttribute(attrs[i]); + for (Attribute attr : attrs) { + addAttribute(attr); } } } @@ -722,8 +718,8 @@ public class MethodGen extends FieldGenOrMethodGen { * Each attribute causes 6 additional header bytes */ int attrs_len = 0; - for (int i = 0; i < code_attrs.length; i++) { - attrs_len += (code_attrs[i].getLength() + 6); + for (Attribute code_attr : code_attrs) { + attrs_len += (code_attr.getLength() + 6); } CodeException[] c_exc = getCodeExceptions(); @@ -734,8 +730,7 @@ public class MethodGen extends FieldGenOrMethodGen { if ((il != null) && !isAbstract()) { // Remove any stale code attribute List<Attribute> attributes = getAttributes(); - for (int i = 0; i < attributes.size(); i++) { - Attribute a = attributes.get(i); + for (Attribute a : attributes) { if (a instanceof Code) { removeAttribute(a); } @@ -897,8 +892,8 @@ public class MethodGen extends FieldGenOrMethodGen { int max = isStatic() ? 0 : 1; if (parameterTypes != null) { - for (int i = 0; i < parameterTypes.length; i++) { - max += parameterTypes[i].getSize(); + for (Type parameterType : parameterTypes) { + max += parameterType.getSize(); } } @@ -985,8 +980,8 @@ public class MethodGen extends FieldGenOrMethodGen { * Initially, populate the branch stack with the exception handlers, because these aren't (necessarily) branched to * explicitly. In each case, the stack will have depth 1, containing the exception object. */ - for (int i = 0, max = et.length; i < max; i++) { - InstructionHandle handlerPos = et[i].getHandlerPC(); + for (CodeExceptionGen codeExceptionGen : et) { + InstructionHandle handlerPos = codeExceptionGen.getHandlerPC(); if (handlerPos != null) { // it must be at least 1 since there is an exception handler maxStackDepth = 1; @@ -1014,8 +1009,8 @@ public class MethodGen extends FieldGenOrMethodGen { // explore all of the select's targets. the default target is handled below. InstructionSelect select = (InstructionSelect) branch; InstructionHandle[] targets = select.getTargets(); - for (int i = 0; i < targets.length; i++) { - branchTargets.push(targets[i], stackDepth); + for (InstructionHandle target : targets) { + branchTargets.push(target, stackDepth); } // nothing to fall through to. ih = null; @@ -1069,8 +1064,8 @@ public class MethodGen extends FieldGenOrMethodGen { StringBuffer buf = new StringBuffer(signature); if (exceptionsThrown.size() > 0) { - for (Iterator<String> e = exceptionsThrown.iterator(); e.hasNext();) { - buf.append("\n\t\tthrows " + e.next()); + for (String s : exceptionsThrown) { + buf.append("\n\t\tthrows " + s); } } @@ -1145,8 +1140,8 @@ public class MethodGen extends FieldGenOrMethodGen { private List /* AnnotationGen */<AnnotationGen> makeMutableVersion(AnnotationGen[] mutableArray) { List<AnnotationGen> result = new ArrayList<AnnotationGen>(); - for (int i = 0; i < mutableArray.length; i++) { - result.add(new AnnotationGen(mutableArray[i], getConstantPool(), false)); + for (AnnotationGen annotationGen : mutableArray) { + result.add(new AnnotationGen(annotationGen, getConstantPool(), false)); } return result; } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ReferenceType.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ReferenceType.java index 1e290f5a4..f29569cb5 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ReferenceType.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/ReferenceType.java @@ -280,10 +280,10 @@ public abstract class ReferenceType extends Type { this_sups[0] = Repository.lookupClass(thiz.getClassName()); t_sups[0] = Repository.lookupClass(other.getClassName()); - for (int i = 0; i < t_sups.length; i++) { - for (int j = 0; j < this_sups.length; j++) { - if (this_sups[j].equals(t_sups[i])) { - return new ObjectType(this_sups[j].getClassName()); + for (JavaClass t_sup : t_sups) { + for (JavaClass this_sup : this_sups) { + if (this_sup.equals(t_sup)) { + return new ObjectType(this_sup.getClassName()); } } } diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/Type.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/Type.java index 9ce007b4f..68b68f3d6 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/Type.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/generic/Type.java @@ -466,8 +466,8 @@ public abstract class Type { StringBuffer sb = new StringBuffer("("); Class[] params = meth.getParameterTypes(); // avoid clone - for (int j = 0; j < params.length; j++) { - sb.append(getType(params[j]).getSignature()); + for (Class param : params) { + sb.append(getType(param).getSignature()); } sb.append(")"); @@ -479,8 +479,8 @@ public abstract class Type { StringBuffer sb = new StringBuffer("("); Class<?>[] params = cons.getParameterTypes(); // avoid clone - for (int j = 0; j < params.length; j++) { - sb.append(getType(params[j]).getSignature()); + for (Class<?> param : params) { + sb.append(getType(param).getSignature()); } sb.append(")V"); diff --git a/bcel-builder/src/main/java/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java b/bcel-builder/src/main/java/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java index a53b9dc35..fe43a7bef 100644 --- a/bcel-builder/src/main/java/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java +++ b/bcel-builder/src/main/java/org/aspectj/apache/bcel/util/NonCachingClassLoaderRepository.java @@ -148,8 +148,7 @@ public class NonCachingClassLoaderRepository implements Repository { public void clear() { processQueue(); Set<Object> keys = map.keySet(); - for (Iterator<Object> iterator = keys.iterator(); iterator.hasNext();) { - Object name = iterator.next(); + for (Object name : keys) { map.remove(name); } } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/BcelTestCase.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/BcelTestCase.java index 7c7013f62..57505a9c5 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/BcelTestCase.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/BcelTestCase.java @@ -54,8 +54,7 @@ public abstract class BcelTestCase extends TestCase { protected Method getMethod(JavaClass cl, String methodname) { Method[] methods = cl.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { if (m.getName().equals(methodname)) { return m; } @@ -65,8 +64,7 @@ public abstract class BcelTestCase extends TestCase { protected Field getField(JavaClass cl, String fieldname) { Field[] fields = cl.getFields(); - for (int i = 0; i < fields.length; i++) { - Field f = fields[i]; + for (Field f : fields) { if (f.getName().equals(fieldname)) { return f; } @@ -96,22 +94,22 @@ public abstract class BcelTestCase extends TestCase { protected Attribute[] findAttribute(String name, JavaClass clazz) { Attribute[] all = clazz.getAttributes(); List<Attribute> chosenAttrsList = new ArrayList<Attribute>(); - for (int i = 0; i < all.length; i++) { + for (Attribute attribute : all) { if (verbose) - System.err.println("Attribute: " + all[i].getName()); - if (all[i].getName().equals(name)) - chosenAttrsList.add(all[i]); + System.err.println("Attribute: " + attribute.getName()); + if (attribute.getName().equals(name)) + chosenAttrsList.add(attribute); } return chosenAttrsList.toArray(new Attribute[] {}); } protected Attribute findAttribute(String name, Attribute[] all) { List<Attribute> chosenAttrsList = new ArrayList<Attribute>(); - for (int i = 0; i < all.length; i++) { + for (Attribute attribute : all) { if (verbose) - System.err.println("Attribute: " + all[i].getName()); - if (all[i].getName().equals(name)) - chosenAttrsList.add(all[i]); + System.err.println("Attribute: " + attribute.getName()); + if (attribute.getName().equals(name)) + chosenAttrsList.add(attribute); } assertTrue("Should be one match: " + chosenAttrsList.size(), chosenAttrsList.size() == 1); return chosenAttrsList.get(0); diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java index 6f5a4f8f3..038a1381e 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/FieldAnnotationsTest.java @@ -102,12 +102,11 @@ public class FieldAnnotationsTest extends BcelTestCase { String annotationName,String annotationElementName,String annotationElementValue) { Field[] fields = clazz.getFields(); - for (int i = 0; i < fields.length; i++) { - Field f = fields[i]; + for (Field f : fields) { AnnotationGen[] fieldAnnotations = f.getAnnotations(); if (f.getName().equals(fieldname)) { - checkAnnotation(fieldAnnotations[0],annotationName,annotationElementName,annotationElementValue); - + checkAnnotation(fieldAnnotations[0], annotationName, annotationElementName, annotationElementValue); + } } } @@ -127,11 +126,10 @@ public class FieldAnnotationsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : a.getValues()) { if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { - fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); + fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue()); } return; } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java index f7ab04d4a..b826fc7a0 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GeneratingAnnotatedClassesTest.java @@ -240,8 +240,7 @@ public class GeneratingAnnotatedClassesTest extends BcelTestCase { assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); List<NameValuePair> l = annotations[0].getValues(); boolean found = false; - for (Iterator<NameValuePair> iter = l.iterator(); iter.hasNext();) { - NameValuePair element = iter.next(); + for (NameValuePair element : l) { if (element.getNameString().equals("dval")) { if (((SimpleElementValue) element.getValue()).stringifyValue().equals("33.4")) found = true; diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java index f64e4440f..b15e5f325 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericSignatureParsingTest.java @@ -187,10 +187,9 @@ public class GenericSignatureParsingTest extends BcelTestCase { public Signature getSignatureAttribute(JavaClass clazz,String name) { Method m = getMethod(clazz,name); Attribute[] as = m.getAttributes(); - for (int i = 0; i < as.length; i++) { - Attribute attribute = as[i]; + for (Attribute attribute : as) { if (attribute.getName().equals("Signature")) { - return (Signature)attribute; + return (Signature) attribute; } } return null; @@ -292,23 +291,23 @@ public class GenericSignatureParsingTest extends BcelTestCase { char[] chars = brackets.toCharArray(); int count = 0; boolean open = false; - - for(int i=0; i<chars.length; i++) { - switch(chars[i]) { - case '[': - if (open) throw new RuntimeException("Illegally nested brackets:" + brackets); - open = true; - break; - - case ']': - if (!open) throw new RuntimeException("Illegally nested brackets:" + brackets); - open = false; - count++; - break; - - default: - } - } + + for (char aChar : chars) { + switch (aChar) { + case '[': + if (open) throw new RuntimeException("Illegally nested brackets:" + brackets); + open = true; + break; + + case ']': + if (!open) throw new RuntimeException("Illegally nested brackets:" + brackets); + open = false; + count++; + break; + + default: + } + } if (open) throw new RuntimeException("Illegally nested brackets:" + brackets); @@ -454,14 +453,14 @@ public class GenericSignatureParsingTest extends BcelTestCase { StringBuffer buf = new StringBuffer("("); if (methodArgs != null) { - for (int i=0; i < methodArgs.length; i++) { - String str = GenericSignatureParsingTest.getSignature(methodArgs[i]); - - if (str.equals("V")) // void can't be a method argument - throw new ClassFormatException("Invalid type: " + methodArgs[i]); - - buf.append(str); - } + for (String methodArg : methodArgs) { + String str = GenericSignatureParsingTest.getSignature(methodArg); + + if (str.equals("V")) // void can't be a method argument + throw new ClassFormatException("Invalid type: " + methodArg); + + buf.append(str); + } } buf.append(")" + GenericSignatureParsingTest.getSignature(returnType)); diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericsErasureTesting.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericsErasureTesting.java index f0e5de738..73f2e6d1b 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericsErasureTesting.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/GenericsErasureTesting.java @@ -38,10 +38,9 @@ public class GenericsErasureTesting extends BcelTestCase { public Signature getSignatureAttribute(JavaClass clazz,String name) { Method m = getMethod(clazz,name); Attribute[] as = m.getAttributes(); - for (int i = 0; i < as.length; i++) { - Attribute attribute = as[i]; + for (Attribute attribute : as) { if (attribute.getName().equals("Signature")) { - return (Signature)attribute; + return (Signature) attribute; } } return null; diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/LocalVariableTypeTableTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/LocalVariableTypeTableTest.java index 41eba95e0..202cd5462 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/LocalVariableTypeTableTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/LocalVariableTypeTableTest.java @@ -45,18 +45,18 @@ public class LocalVariableTypeTableTest extends BcelTestCase { boolean tc1OK = false; boolean tc2OK = false; String errormessage = null; - for (int i = 0; i < lvtable.length; i++) { - String sig = Utility.signatureToString(lvtable[i].getSignature()); - if (lvtable[i].getName().equals("tc1")) { + for (LocalVariable localVariable : lvtable) { + String sig = Utility.signatureToString(localVariable.getSignature()); + if (localVariable.getName().equals("tc1")) { if (!sig.equals("TreasureChest<String>")) { - errormessage="Expected signature of 'TreasureChest<String>' for tc1 but got "+sig; + errormessage = "Expected signature of 'TreasureChest<String>' for tc1 but got " + sig; } else { tc1OK = true; } } - if (lvtable[i].getName().equals("tc2")) { + if (localVariable.getName().equals("tc2")) { if (!sig.equals("TreasureChest<Integer>")) { - errormessage="Expected signature of 'TreasureChest<Integer>' for tc2 but got "+sig; + errormessage = "Expected signature of 'TreasureChest<Integer>' for tc2 but got " + sig; } else { tc2OK = true; } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java index 14d009cf0..8876813d2 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/MethodAnnotationsTest.java @@ -63,12 +63,11 @@ public class MethodAnnotationsTest extends BcelTestCase { String annotationName,String annotationElementName,String annotationElementValue) { Method[] methods = clazz.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { AnnotationGen[] methodAnnotations = m.getAnnotations(); if (m.getName().equals(methodname)) { - checkAnnotation(methodAnnotations[0],annotationName,annotationElementName,annotationElementValue); - + checkAnnotation(methodAnnotations[0], annotationName, annotationElementName, annotationElementValue); + } } } @@ -88,11 +87,10 @@ public class MethodAnnotationsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : a.getValues()) { if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { - fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); + fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue()); } return; } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java index 0e9c4fadd..f49b4fb46 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/ParameterAnnotationsTest.java @@ -271,8 +271,8 @@ public class ParameterAnnotationsTest extends BcelTestCase { private Method findMethod(ClassGen c,String mname) { Method[] ms = c.getMethods(); - for (int i = 0; i < ms.length; i++) { - if (ms[i].getName().equals(mname)) return ms[i]; + for (Method m : ms) { + if (m.getName().equals(mname)) return m; } return null; } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java index 669d942f5..af3df5c6a 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleAnnotationAttributeTest.java @@ -208,11 +208,10 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { } private void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : a.getValues()) { if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { - fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); + fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue()); } return; } @@ -385,8 +384,7 @@ public class RuntimeVisibleAnnotationAttributeTest extends BcelTestCase { public static List<String> getListOfAnnotationNames(AnnotationGen a) { List<NameValuePair> l = a.getValues(); List<String> names = new ArrayList<String>(); - for (Iterator<NameValuePair> i = l.iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : l) { names.add(element.getNameString()); } return names; diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java index 1b8af7419..eb594974c 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/RuntimeVisibleParameterAnnotationAttributeTest.java @@ -38,30 +38,29 @@ public class RuntimeVisibleParameterAnnotationAttributeTest extends BcelTestCase Attribute[] rvaAttr = findAttribute("RuntimeVisibleParameterAnnotations",clazz); Method[] methods = clazz.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { if (m.getName().equals("foo")) { - RuntimeVisParamAnnos paramAnns = - (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations",m.getAttributes()); - assertTrue("foo takes two parameters, not "+paramAnns.getParameterAnnotations().size(), - paramAnns.getParameterAnnotations().size()==2); + RuntimeVisParamAnnos paramAnns = + (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations", m.getAttributes()); + assertTrue("foo takes two parameters, not " + paramAnns.getParameterAnnotations().size(), + paramAnns.getParameterAnnotations().size() == 2); AnnotationGen[] firstParamAnnotations = paramAnns.getAnnotationsOnParameter(0); - checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","2"); + checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "2"); AnnotationGen[] secondParamAnnotations = paramAnns.getAnnotationsOnParameter(1); - checkAnnotation(secondParamAnnotations[0],"SimpleAnnotation","id","3"); - checkAnnotation(secondParamAnnotations[1],"AnnotationEnumElement","enumval","LSimpleEnum;Red"); - + checkAnnotation(secondParamAnnotations[0], "SimpleAnnotation", "id", "3"); + checkAnnotation(secondParamAnnotations[1], "AnnotationEnumElement", "enumval", "LSimpleEnum;Red"); + } if (m.getName().equals("main")) { - RuntimeVisParamAnnos paramAnns = - (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations",m.getAttributes()); - assertTrue("main takes one parameter, not "+paramAnns.getParameterAnnotations().size(), - paramAnns.getParameterAnnotations().size()==1); + RuntimeVisParamAnnos paramAnns = + (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations", m.getAttributes()); + assertTrue("main takes one parameter, not " + paramAnns.getParameterAnnotations().size(), + paramAnns.getParameterAnnotations().size() == 1); AnnotationGen[] firstParamAnnotations = paramAnns.getAnnotationsOnParameter(0); - checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","1"); + checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "1"); } } } @@ -94,17 +93,16 @@ public class RuntimeVisibleParameterAnnotationAttributeTest extends BcelTestCase public void checkFooMethod(JavaClass clazz) { Method[] methods = clazz.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { if (m.getName().equals("foo")) { AnnotationGen[] firstParamAnnotations = m.getAnnotationsOnParameter(0); - checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","2"); + checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "2"); AnnotationGen[] secondParamAnnotations = m.getAnnotationsOnParameter(1); - checkAnnotation(secondParamAnnotations[0],"SimpleAnnotation","id","3"); - checkAnnotation(secondParamAnnotations[1],"AnnotationEnumElement","enumval","LSimpleEnum;Red"); - + checkAnnotation(secondParamAnnotations[0], "SimpleAnnotation", "id", "3"); + checkAnnotation(secondParamAnnotations[1], "AnnotationEnumElement", "enumval", "LSimpleEnum;Red"); + } } } @@ -124,11 +122,10 @@ public class RuntimeVisibleParameterAnnotationAttributeTest extends BcelTestCase // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : a.getValues()) { if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { - fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); + fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue()); } return; } diff --git a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java index 877594728..bf41bb3c1 100644 --- a/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java +++ b/bcel-builder/src/test/java/org/aspectj/apache/bcel/classfile/tests/VarargsTest.java @@ -65,11 +65,10 @@ public class VarargsTest extends BcelTestCase { public void checkMarkedVarargs(JavaClass clazz,String methodname,boolean shouldBeMarked) { Method[] methods = clazz.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { if (m.getName().equals(methodname)) { - assertTrue("Method '"+methodname+"' should answer varargs="+shouldBeMarked, - m.isVarargs()==shouldBeMarked); + assertTrue("Method '" + methodname + "' should answer varargs=" + shouldBeMarked, + m.isVarargs() == shouldBeMarked); } } } @@ -78,11 +77,10 @@ public class VarargsTest extends BcelTestCase { // helper methods public void checkValue(AnnotationGen a,String name,String tostring) { - for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) { - NameValuePair element = i.next(); + for (NameValuePair element : a.getValues()) { if (element.getNameString().equals(name)) { if (!element.getValue().stringifyValue().equals(tostring)) { - fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue()); + fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue()); } return; } diff --git a/bridge/src/main/java/org/aspectj/bridge/MessageUtil.java b/bridge/src/main/java/org/aspectj/bridge/MessageUtil.java index 6d85ea6f9..0393a5a58 100644 --- a/bridge/src/main/java/org/aspectj/bridge/MessageUtil.java +++ b/bridge/src/main/java/org/aspectj/bridge/MessageUtil.java @@ -1101,8 +1101,8 @@ public class MessageUtil { return true; } boolean result = true; - for (int i = 0; i < sources.length; i++) { - if (!sink.handleMessage(sources[i])) { + for (IMessage source : sources) { + if (!sink.handleMessage(source)) { if (fastFail) { return false; } diff --git a/bridge/src/test/java/org/aspectj/bridge/MessageTest.java b/bridge/src/test/java/org/aspectj/bridge/MessageTest.java index be30c48ba..d3bd73be6 100644 --- a/bridge/src/test/java/org/aspectj/bridge/MessageTest.java +++ b/bridge/src/test/java/org/aspectj/bridge/MessageTest.java @@ -74,18 +74,18 @@ public class MessageTest extends TestCase { public void testKind_isSameOrLessThan() { IMessage.Kind last; IMessage.Kind next = null; - for (Iterator<IMessage.Kind> iter = IMessage.KINDS.iterator(); iter.hasNext();) { - last = next; - next = iter.next(); - if (null == last) { - continue; - } - String label = "last: " + last + " next: " + next; - assertTrue(label, !next.isSameOrLessThan(null)); - assertTrue(label, !next.isSameOrLessThan(last)); - assertTrue(label, last.isSameOrLessThan(next)); - assertTrue(label, next.isSameOrLessThan(next)); - } + for (IMessage.Kind kind : IMessage.KINDS) { + last = next; + next = kind; + if (null == last) { + continue; + } + String label = "last: " + last + " next: " + next; + assertTrue(label, !next.isSameOrLessThan(null)); + assertTrue(label, !next.isSameOrLessThan(last)); + assertTrue(label, last.isSameOrLessThan(next)); + assertTrue(label, next.isSameOrLessThan(next)); + } } public void testMessageHandler() { diff --git a/build/src/main/java/$installer$/org/aspectj/Main.java b/build/src/main/java/$installer$/org/aspectj/Main.java index 6ecebae63..2ffc8b889 100644 --- a/build/src/main/java/$installer$/org/aspectj/Main.java +++ b/build/src/main/java/$installer$/org/aspectj/Main.java @@ -707,8 +707,8 @@ class InstallContext { public boolean isTextFile(File file) { String name = file.getName(); - for (int i = 0; i < TEXT_EXTENSIONS.length; i++) { - if (name.endsWith(TEXT_EXTENSIONS[i])) { + for (String textExtension : TEXT_EXTENSIONS) { + if (name.endsWith(textExtension)) { return true; } } @@ -1243,10 +1243,9 @@ class ConfigureLauncherPane extends WizardPane { paths = unixPaths; } - for (int suffixIndex = 0; suffixIndex < suffixes.length; suffixIndex++) { - String suffix = suffixes[suffixIndex]; - for (int prefixIndex = 0; prefixIndex < paths.length; prefixIndex++) { - String prefix = paths[prefixIndex]; + for (String suffix : suffixes) { + for (String path : paths) { + String prefix = path; prefix = applyProperties(prefix); File test = new File(prefix + suffix); if (isLegalJavaHome(test)) { diff --git a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AJInstaller.java b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AJInstaller.java index 2428e66d9..809ac1cbb 100644 --- a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AJInstaller.java +++ b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AJInstaller.java @@ -152,11 +152,10 @@ public class AJInstaller extends MatchingTask { StringBuffer buf = new StringBuffer(); buf.append(contentsBytes); buf.append(NEWLINE); - for (Iterator<String> i = contentsNames.iterator(); i.hasNext(); ) { - String name = i.next(); - buf.append(name); - buf.append(NEWLINE); - } + for (String name : contentsNames) { + buf.append(name); + buf.append(NEWLINE); + } zipFile(new StringBufferInputStream(buf.toString()), zOut, CONTENTS_FILE, System.currentTimeMillis()); } @@ -347,19 +346,19 @@ public class AJInstaller extends MatchingTask { } protected void writeDirs(ZipOutputStream zOut, String[] dirs) throws IOException { - for (int i = 0; i < dirs.length; i++) { - File f = new File(baseDir,dirs[i]); - String name = dirs[i].replace(File.separatorChar,'/')+"/"; - zipDir(f, zOut, name); - } + for (String dir : dirs) { + File f = new File(baseDir, dir); + String name = dir.replace(File.separatorChar, '/') + "/"; + zipDir(f, zOut, name); + } } protected void writeFiles(ZipOutputStream zOut, String[] files) throws IOException { - for (int i = 0; i < files.length; i++) { - File f = new File(baseDir,files[i]); - String name = files[i].replace(File.separatorChar,'/'); - zipFile(f, zOut, name); - } + for (String file : files) { + File f = new File(baseDir, file); + String name = file.replace(File.separatorChar, '/'); + zipFile(f, zOut, name); + } } } diff --git a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.java b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.java index c4f8848d8..bef3fb0aa 100644 --- a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.java +++ b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/AntBuilder.java @@ -95,8 +95,7 @@ public class AntBuilder extends Builder { Result[] reqs = result.getRequired(); StringBuffer depends = new StringBuffer(); boolean first = true; - for (int i = 0; i < reqs.length; i++) { - Result reqResult = reqs[i]; + for (Result reqResult : reqs) { if (!first) { depends.append(","); } else { @@ -110,8 +109,7 @@ public class AntBuilder extends Builder { targets.put(resultTargetName, target); // then recursively add any required results - for (int i = 0; i < reqs.length; i++) { - Result reqResult = reqs[i]; + for (Result reqResult : reqs) { makeTargetsForResult(reqResult, targets); } } @@ -311,8 +309,7 @@ public class AntBuilder extends Builder { public boolean setupClasspath(Result result, Path classpath) { // XXX fix test access boolean hasLibraries = false; // required libraries - for (Iterator<File> iter = result.getLibJars().iterator(); iter.hasNext();) { - File file = iter.next(); + for (File file : result.getLibJars()) { classpath.createPathElement().setLocation(file); if (!hasLibraries) { hasLibraries = true; @@ -321,16 +318,15 @@ public class AntBuilder extends Builder { // Westodo Kind kind = result.getKind(); Result[] reqs = result.getRequired(); // required modules and their exported libraries - for (int i = 0; i < reqs.length; i++) { - Result requiredResult = reqs[i]; + for (Result requiredResult : reqs) { classpath.createPathElement().setLocation(requiredResult.getOutputFile()); if (!hasLibraries) { hasLibraries = true; } // also put on classpath libraries exported from required module // XXX exported modules not supported - for (Iterator<File> iterator = requiredResult.getExportedLibJars().iterator(); iterator.hasNext();) { - classpath.createPathElement().setLocation(iterator.next()); + for (File file : requiredResult.getExportedLibJars()) { + classpath.createPathElement().setLocation(file); } } return hasLibraries; @@ -424,8 +420,7 @@ public class AntBuilder extends Builder { return new Result[0]; } ArrayList<String> toReturn = new ArrayList<String>(); - for (Iterator<Target> iter = result.iterator(); iter.hasNext();) { - Target target = iter.next(); + for (Target target : result) { String name = target.getName(); if (null == name) { throw new Error("null name?"); diff --git a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/ConditionalTask.java b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/ConditionalTask.java index ccb9c2149..e71795912 100644 --- a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/ConditionalTask.java +++ b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/ConditionalTask.java @@ -145,11 +145,11 @@ public abstract class ConditionalTask extends Task { return isOneOf(prop, trues) || isOneOf(prop, complement(falses)); } private boolean isOneOf(String prop, String[] strings) { - for (int i = 0; i < strings.length; i++) { - if (strings[i].equals(prop)) { - return true; - } - } + for (String string : strings) { + if (string.equals(prop)) { + return true; + } + } return false; } private String[] complement(String[] strings) { diff --git a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java index a33505d95..61e29f3b3 100644 --- a/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java +++ b/build/src/main/java/org/aspectj/internal/tools/ant/taskdefs/StripNonBodyHtml.java @@ -81,13 +81,13 @@ public class StripNonBodyHtml extends MatchingTask { log("stripping " + files.length + " files"); int stripped = 0; - for (int i = 0, len = files.length; i < len; i++) { - if (processFile(files[i])) { - stripped++; - } else { - log(files[i] + " not stripped"); - } - } + for (String file : files) { + if (processFile(file)) { + stripped++; + } else { + log(file + " not stripped"); + } + } log(stripped + " files successfully stripped"); } diff --git a/build/src/main/java/org/aspectj/internal/tools/build/Builder.java b/build/src/main/java/org/aspectj/internal/tools/build/Builder.java index 8efea662a..1d7bfa7d8 100644 --- a/build/src/main/java/org/aspectj/internal/tools/build/Builder.java +++ b/build/src/main/java/org/aspectj/internal/tools/build/Builder.java @@ -281,10 +281,10 @@ public abstract class Builder { } finally { if (0 < errors.size()) { String label = "error building " + buildSpec + ": "; - for (Iterator<String> iter = errors.iterator(); iter.hasNext();) { - String m = label + iter.next(); - handler.error(m); - } + for (String error : errors) { + String m = label + error; + handler.error(m); + } } } } @@ -294,15 +294,15 @@ public abstract class Builder { */ public boolean cleanup() { boolean noErr = true; - for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!Util.deleteContents(file) || !file.delete()) { - if (noErr) { - noErr = false; - } - handler.log("unable to clean up " + file); - } - } + for (Object tempFile : tempFiles) { + File file = (File) tempFile; + if (!Util.deleteContents(file) || !file.delete()) { + if (noErr) { + noErr = false; + } + handler.log("unable to clean up " + file); + } + } return noErr; } @@ -345,19 +345,18 @@ public abstract class Builder { if (isLogging()) { handler.log("modules to build: " + Arrays.asList(buildList)); } - for (int i = 0; i < buildList.length; i++) { - Result required = buildList[i]; - if (!buildingEnabled) { - return false; - } - String requiredName = required.getName(); - if (!doneList.contains(requiredName)) { - doneList.add(requiredName); - if (!buildOnly(required, errors)) { - return false; - } - } - } + for (Result required : buildList) { + if (!buildingEnabled) { + return false; + } + String requiredName = required.getName(); + if (!doneList.contains(requiredName)) { + doneList.add(requiredName); + if (!buildOnly(required, errors)) { + return false; + } + } + } } return true; } @@ -439,14 +438,14 @@ public abstract class Builder { handler); ProductModule[] productModules = discoverModules(buildSpec.productDir, modules); - for (int i = 0; i < productModules.length; i++) { - if (buildSpec.verbose) { - handler.log("building product module " + productModules[i]); - } - if (!buildProductModule(productModules[i])) { - return false; - } - } + for (ProductModule module : productModules) { + if (buildSpec.verbose) { + handler.log("building product module " + module); + } + if (!buildProductModule(module)) { + return false; + } + } if (buildSpec.verbose) { handler.log("assembling product module for " + buildSpec); } @@ -476,12 +475,12 @@ public abstract class Builder { String excludes = null; { StringBuffer buf = new StringBuffer(); - for (int i = 0; i < productModules.length; i++) { - if (0 < buf.length()) { - buf.append(","); - } - buf.append(productModules[i].relativePath); - } + for (ProductModule productModule : productModules) { + if (0 < buf.length()) { + buf.append(","); + } + buf.append(productModule.relativePath); + } if (0 < buf.length()) { excludes = buf.toString(); } @@ -492,14 +491,13 @@ public abstract class Builder { } // copy binaries associated with module flag files - for (int i = 0; i < productModules.length; i++) { - final ProductModule product = productModules[i]; - final Kind kind = Result.kind(Result.NORMAL, product.assembleAll); - Result result = product.module.getResult(kind); - String targPath = Util.path(targDirPath, product.relativePath); - File jarFile = result.getOutputFile(); - copyFile(jarFile, new File(targPath), FILTER_OFF); - } + for (final ProductModule product : productModules) { + final Kind kind = Result.kind(Result.NORMAL, product.assembleAll); + Result result = product.module.getResult(kind); + String targPath = Util.path(targDirPath, product.relativePath); + File jarFile = result.getOutputFile(); + copyFile(jarFile, new File(targPath), FILTER_OFF); + } handler.log("created product in " + targDir); // ---- create installer @@ -533,9 +531,9 @@ public abstract class Builder { Result result = module.module.getResult(productKind); return buildAll(result, errors); } finally { - for (Iterator<String> iter = errors.iterator(); iter.hasNext();) { - handler.error("error building " + module + ": " + iter.next()); - } + for (String error : errors) { + handler.error("error building " + module + ": " + error); + } } } @@ -595,13 +593,12 @@ public abstract class Builder { File library = liter.next(); final String fname = library.getName(); if (null != fname) { - for (Iterator<String> iter = SKIP_LIBRARIES.iterator(); iter.hasNext();) { - String name = iter.next(); - if (fname.equals(name)) { - liter.remove(); - break; - } - } + for (String name : SKIP_LIBRARIES) { + if (fname.equals(name)) { + liter.remove(); + break; + } + } } } } diff --git a/build/src/main/java/org/aspectj/internal/tools/build/Module.java b/build/src/main/java/org/aspectj/internal/tools/build/Module.java index 58789424f..acc8fd90b 100644 --- a/build/src/main/java/org/aspectj/internal/tools/build/Module.java +++ b/build/src/main/java/org/aspectj/internal/tools/build/Module.java @@ -79,13 +79,13 @@ public class Module { return; } File[] files = srcDir.listFiles(); - for (int i = 0; i < files.length; i++) { - if (files[i].isDirectory()) { - sourceFiles(files[i], result); - } else if (isSourceFile(files[i])) { - result.add(files[i]); - } - } + for (File file : files) { + if (file.isDirectory()) { + sourceFiles(file, result); + } else if (isSourceFile(file)) { + result.add(file); + } + } } private static void addIfNew(List<File> source, List<File> sink) { @@ -107,14 +107,13 @@ public class Module { addIfNew(result.getLibJars(), known); addIfNew(result.getExportedLibJars(), known); Result[] reqs = result.getRequired(); - for (int i = 0; i < reqs.length; i++) { - Result requiredResult = reqs[i]; - File requiredJar = requiredResult.getOutputFile(); - if (!known.contains(requiredJar)) { - known.add(requiredJar); - doFindJarRequirements(requiredResult, known); - } - } + for (Result requiredResult : reqs) { + File requiredJar = requiredResult.getOutputFile(); + if (!known.contains(requiredJar)) { + known.add(requiredJar); + doFindJarRequirements(requiredResult, known); + } + } } /** @return true if this is a source file */ @@ -238,31 +237,29 @@ public class Module { } final long time = outputFile.lastModified(); File file; - for (Iterator<File> iter = result.getSrcDirs().iterator(); iter.hasNext();) { - File srcDir = iter.next(); - for (Iterator<File> srcFiles = sourceFiles(srcDir); srcFiles.hasNext();) { - file = srcFiles.next(); - if (outOfDate(time, file)) { - return true; - } - } - } + for (File srcDir : result.getSrcDirs()) { + for (Iterator<File> srcFiles = sourceFiles(srcDir); srcFiles.hasNext(); ) { + file = srcFiles.next(); + if (outOfDate(time, file)) { + return true; + } + } + } // required modules Result[] reqs = result.getRequired(); - for (int i = 0; i < reqs.length; i++) { - Result requiredResult = reqs[i]; - file = requiredResult.getOutputFile(); - if (outOfDate(time, file)) { - return true; - } - } + for (Result requiredResult : reqs) { + file = requiredResult.getOutputFile(); + if (outOfDate(time, file)) { + return true; + } + } // libraries - for (Iterator<File> iter = result.getLibJars().iterator(); iter.hasNext();) { - file = iter.next(); - if (outOfDate(time, file)) { - return true; - } - } + for (File value : result.getLibJars()) { + file = value; + if (outOfDate(time, file)) { + return true; + } + } return false; } @@ -345,14 +342,13 @@ public class Module { Util.closeSilently(fin); } RequiredBundle[] bundles = bundle.getRequiredBundles(); - for (int i = 0; i < bundles.length; i++) { - RequiredBundle required = bundles[i]; - update("src", "/" + required.name, required.text, false); - } + for (RequiredBundle required : bundles) { + update("src", "/" + required.name, required.text, false); + } String[] libs = bundle.getClasspath(); - for (int i = 0; i < libs.length; i++) { - update("lib", libs[i], libs[i], false); - } + for (String lib : libs) { + update("lib", lib, lib, false); + } return true; } @@ -478,11 +474,11 @@ public class Module { private void warnVariable(String path, String toString) { String[] known = { "JRE_LIB", "ASPECTJRT_LIB", "JRE15_LIB" }; - for (int i = 0; i < known.length; i++) { - if (known[i].equals(path)) { - return; - } - } + for (String s : known) { + if (s.equals(path)) { + return; + } + } messager.log("Module cannot handle var yet: " + toString); } @@ -645,9 +641,9 @@ public class Module { public void acceptLine(String line) { String[] tokens = tokenize(line); - for (int i = 0; i < tokens.length; i++) { - next(tokens[i]); - } + for (String token : tokens) { + next(token); + } } private Properties attributesToProperties() { diff --git a/build/src/main/java/org/aspectj/internal/tools/build/SampleGatherer.java b/build/src/main/java/org/aspectj/internal/tools/build/SampleGatherer.java index 4e9f59011..4df90dbbe 100644 --- a/build/src/main/java/org/aspectj/internal/tools/build/SampleGatherer.java +++ b/build/src/main/java/org/aspectj/internal/tools/build/SampleGatherer.java @@ -89,9 +89,9 @@ public class SampleGatherer { return; } Samples result = new Samples(); - for (int i = 0; i < args.length; i++) { - result = gather(new File(args[i]), result); - } + for (String arg : args) { + result = gather(new File(arg), result); + } StringBuffer sb = HTMLSamplesRenderer.ME.render(result, null); @@ -144,9 +144,9 @@ public class SampleGatherer { } } else if (source.isDirectory() && source.canRead()) { File[] files = source.listFiles(); - for (int i = 0; i < files.length; i++) { - doGather(files[i], sink); - } + for (File file : files) { + doGather(file, sink); + } } } @@ -156,11 +156,11 @@ public class SampleGatherer { } String path = file.getName().toLowerCase(); String[] suffixes = Sample.Kind.SOURCE_SUFFIXES; - for (int i = 0; i < suffixes.length; i++) { - if (path.endsWith(suffixes[i])) { - return true; - } - } + for (String suffix : suffixes) { + if (path.endsWith(suffix)) { + return true; + } + } return false; } @@ -451,7 +451,8 @@ class SamplesRenderer { public static final String COPYRIGHT = "<p><small>Copyright 2003 Contributors. All Rights Reserved. " - + "This sample code is made available under the Common Public "
+ "License version 1.0 available at " + + "This sample code is made available under the Common Public " + + "License version 1.0 available at " + "<a href=\"http://www.eclipse.org/legal/epl-v10.html\">" + "http://www.eclipse.org/legal/epl-v10.html</a>." + "Contributors are listed in this document as authors. " @@ -473,18 +474,16 @@ class SamplesRenderer { startList(samples, sink); List<Sample> list = samples.getSortedSamples(); String anchorName = null; - for (ListIterator<Sample> iter = list.listIterator(); - iter.hasNext();) { - Sample sample = iter.next(); - String newAnchorName = sample.anchorName; - if ((null == anchorName) - || (!anchorName.equals(newAnchorName))) { - endAnchorName(anchorName, sink); - startAnchorName(newAnchorName, sample.anchorTitle, sink); - anchorName = newAnchorName; - } - render(sample, sink); - } + for (Sample sample : list) { + String newAnchorName = sample.anchorName; + if ((null == anchorName) + || (!anchorName.equals(newAnchorName))) { + endAnchorName(anchorName, sink); + startAnchorName(newAnchorName, sample.anchorTitle, sink); + anchorName = newAnchorName; + } + render(sample, sink); + } endAnchorName(anchorName, sink); endList(samples, sink); return sink; @@ -605,17 +604,16 @@ class HTMLSamplesRenderer extends SamplesRenderer { sampleSection.append(EOL); if (doFlags) { boolean flagHeaderDone = false; - for (Iterator iter = sample.flags.iterator(); iter.hasNext();) { - String flag = (String) iter.next(); - if (!flagHeaderDone) { - sampleSection.append("<p>Comments flagged:<ul>"); - sampleSection.append(EOL); - flagHeaderDone = true; - } - sampleSection.append("<li>"); - sampleSection.append(flag); - sampleSection.append("</li>"); - } + for (String flag : sample.flags) { + if (!flagHeaderDone) { + sampleSection.append("<p>Comments flagged:<ul>"); + sampleSection.append(EOL); + flagHeaderDone = true; + } + sampleSection.append("<li>"); + sampleSection.append(flag); + sampleSection.append("</li>"); + } if (flagHeaderDone) { sampleSection.append("</ul>"); sampleSection.append(EOL); @@ -779,30 +777,29 @@ class HTMLSamplesRenderer extends SamplesRenderer { sink.append("<h2><a name=\"authorIndex\"></a>Author Index</h2>"); List<Sample> list = samples.getSortedSamples(Sample.AUTHOR_NAME_SOURCE_COMPARER); String lastAuthor = null; - for (ListIterator<Sample> iter = list.listIterator(); iter.hasNext();) { - Sample sample = iter.next(); - String author = sample.author; - if (!author.equals(lastAuthor)) { - if (null != lastAuthor) { - sink.append("</li></ul>"); - } - sink.append("<li>"); - sink.append(author); - sink.append(EOL); - sink.append("<ul>"); - sink.append(EOL); - lastAuthor = author; - } - sink.append(" <li><a href=\"#"); - sink.append(sample.anchorName); - sink.append("\">"); - if (null == sample.anchorTitle) { - sink.append(sample.anchorName); - } else { - sink.append(sample.anchorTitle); - } - sink.append("</a></li>"); - } + for (Sample sample : list) { + String author = sample.author; + if (!author.equals(lastAuthor)) { + if (null != lastAuthor) { + sink.append("</li></ul>"); + } + sink.append("<li>"); + sink.append(author); + sink.append(EOL); + sink.append("<ul>"); + sink.append(EOL); + lastAuthor = author; + } + sink.append(" <li><a href=\"#"); + sink.append(sample.anchorName); + sink.append("\">"); + if (null == sample.anchorTitle) { + sink.append(sample.anchorName); + } else { + sink.append(sample.anchorTitle); + } + sink.append("</a></li>"); + } } } @@ -812,11 +809,10 @@ class SampleUtil { public static void simpleRender(Samples result, StringBuffer sink) { List sortedSamples = result.getSortedSamples(); int i = 0; - for (ListIterator iter = sortedSamples.listIterator(); - iter.hasNext();) { - Sample sample = (Sample) iter.next(); - sink.append(i++ + ": " + sample); - } + for (Object sortedSample : sortedSamples) { + Sample sample = (Sample) sortedSample; + sink.append(i++ + ": " + sample); + } } /** result struct for getPackagePath */ diff --git a/build/src/main/java/org/aspectj/internal/tools/build/Util.java b/build/src/main/java/org/aspectj/internal/tools/build/Util.java index 9a1eb9abc..dd393ce45 100644 --- a/build/src/main/java/org/aspectj/internal/tools/build/Util.java +++ b/build/src/main/java/org/aspectj/internal/tools/build/Util.java @@ -193,10 +193,10 @@ public class Util { return false; } else if (dir.isDirectory()) { File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - if (!deleteContents(files[i]) || !files[i].delete()) { - return false; - } + for (File file : files) { + if (!deleteContents(file) || !file.delete()) { + return false; + } } } return true; @@ -293,26 +293,26 @@ public class Util { if ((hits != expected.length) || (hits != actual.length)) { sb.append("unexpected ["); String prefix = ""; - for (int i = 0; i < actual.length; i++) { - if (null != actual[i]) { - sb.append(prefix); - prefix = ", "; - sb.append("\""); - sb.append(actual[i]); - sb.append("\""); - } - } + for (String value : actual) { + if (null != value) { + sb.append(prefix); + prefix = ", "; + sb.append("\""); + sb.append(value); + sb.append("\""); + } + } sb.append("] missing ["); prefix = ""; - for (int i = 0; i < expected.length; i++) { - if (null != expected[i]) { - sb.append(prefix); - prefix = ", "; - sb.append("\""); - sb.append(expected[i]); - sb.append("\""); - } - } + for (String s : expected) { + if (null != s) { + sb.append(prefix); + prefix = ", "; + sb.append("\""); + sb.append(s); + sb.append("\""); + } + } sb.append("]"); return true; } diff --git a/build/src/test/java/org/aspectj/build/BuildModuleTests.java b/build/src/test/java/org/aspectj/build/BuildModuleTests.java index 7f7550279..042548d3f 100644 --- a/build/src/test/java/org/aspectj/build/BuildModuleTests.java +++ b/build/src/test/java/org/aspectj/build/BuildModuleTests.java @@ -114,8 +114,8 @@ public class BuildModuleTests extends TestCase { public void testLicense_org_eclipse_jdt_core() { final String mod = "org.eclipse.jdt.core"; final String pre = BASE_DIR + mod + File.separator; - for (int i = 0; i < JDT_SOURCE_DIRS.length; i++) { - checkSourceDirectory(new File(pre + JDT_SOURCE_DIRS[i]), mod); + for (String jdtSourceDir : JDT_SOURCE_DIRS) { + checkSourceDirectory(new File(pre + jdtSourceDir), mod); } } @@ -167,10 +167,10 @@ public class BuildModuleTests extends TestCase { void checkLicense(String module) { File moduleDir = new File(Util.path("..", module)); File[] srcDirs = findSourceRoots(moduleDir); - for (int i = 0; i < srcDirs.length; i++) { - System.out.println(srcDirs[i]); - checkSourceDirectory(srcDirs[i], module); - } + for (File srcDir : srcDirs) { + System.out.println(srcDir); + checkSourceDirectory(srcDir, module); + } } void checkSourceDirectory(File srcDir, String module) { @@ -294,17 +294,16 @@ public class BuildModuleTests extends TestCase { } void unknownFiles(File dir, ArrayList<File> results) { File[] files = dir.listFiles(this); - for (int j = 0; j < files.length; j++) { - File file = files[j]; - if (file.isDirectory()) { - String name = file.getName(); - if (!("CVS".equals(name))) { - unknownFiles(file, results); - } - } else { - results.add(file); - } - } + for (File file : files) { + if (file.isDirectory()) { + String name = file.getName(); + if (!("CVS".equals(name))) { + unknownFiles(file, results); + } + } else { + results.add(file); + } + } } } diff --git a/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java b/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java index 4a949b447..81600ca94 100644 --- a/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java +++ b/build/src/test/java/org/aspectj/internal/build/BuildModuleTest.java @@ -106,24 +106,23 @@ public class BuildModuleTest extends TestCase { } protected void deleteTempFiles() { - for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!Util.delete(file)) { - File[] list = file.listFiles(); - if (!Util.isEmpty(list)) { - StringBuffer sb = new StringBuffer(); - sb.append("warning: BuildModuleTest unable to delete "); - sb.append(file.toString()); - sb.append("\n"); // XXX platform - for (int i = 0; i < list.length; i++) { - sb.append(" "); - sb.append(list[i].toString()); - sb.append("\n"); // XXX platform - } - System.err.println(sb.toString()); - } - } - } + for (File file : tempFiles) { + if (!Util.delete(file)) { + File[] list = file.listFiles(); + if (!Util.isEmpty(list)) { + StringBuffer sb = new StringBuffer(); + sb.append("warning: BuildModuleTest unable to delete "); + sb.append(file.toString()); + sb.append("\n"); // XXX platform + for (File value : list) { + sb.append(" "); + sb.append(value.toString()); + sb.append("\n"); // XXX platform + } + System.err.println(sb.toString()); + } + } + } } public void testAllJunitTests() { @@ -318,21 +317,21 @@ public class BuildModuleTest extends TestCase { printedMessage = true; } if (debugging()) { - for (int i = 0; i < DEBUGS.length; i++) { - if (target.equals(DEBUGS[i])) { - return true; - } - } + for (String debug : DEBUGS) { + if (target.equals(debug)) { + return true; + } + } return false; } else { - for (int i = 0; i < SKIPS.length; i++) { - if (SKIPS[i].equals(target)) { - if (printInfoMessages) { - System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]"); - } - return false; - } - } + for (String skip : SKIPS) { + if (skip.equals(target)) { + if (printInfoMessages) { + System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]"); + } + return false; + } + } } return building; } @@ -419,10 +418,10 @@ public class BuildModuleTest extends TestCase { java.setClasspath(cp); java.setClassname(classname); if (null != args) { - for (int i = 0; i < args.length; i++) { - Argument arg = java.createArg(); - arg.setValue(args[i]); - } + for (String s : args) { + Argument arg = java.createArg(); + arg.setValue(s); + } } try { java.execute(); diff --git a/build/src/test/java/org/aspectj/internal/build/ModulesTest.java b/build/src/test/java/org/aspectj/internal/build/ModulesTest.java index 496cde051..383b3859d 100644 --- a/build/src/test/java/org/aspectj/internal/build/ModulesTest.java +++ b/build/src/test/java/org/aspectj/internal/build/ModulesTest.java @@ -62,12 +62,12 @@ public class ModulesTest extends TestCase { } else { File[] files = file.listFiles(); boolean result = true; - for (int i = 0; i < files.length; i++) { - if (!ModulesTest.delete(files[i]) - && result) { - result = false; - } - } + for (File value : files) { + if (!ModulesTest.delete(value) + && result) { + result = false; + } + } return (file.delete() && result); } } @@ -80,11 +80,10 @@ public class ModulesTest extends TestCase { protected void tearDown() throws Exception { super.tearDown(); - for (Iterator<File> iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (!ModulesTest.delete(file)) { - System.err.println("warning: ModulesTest unable to delete " + file); - } + for (File file : tempFiles) { + if (!ModulesTest.delete(file)) { + System.err.println("warning: ModulesTest unable to delete " + file); + } } } @@ -270,13 +269,13 @@ public class ModulesTest extends TestCase { File libDir = new File(distDir, "tools/lib"); String[] jars = { "tools", "rt", "weaver", "lib"}; - for (int i = 0; i < jars.length; i++) { - File jar = new File(libDir, "aspectj" + jars[i] + ".jar"); - assertTrue(jar.getPath(), jar.canRead()); - if (10 > jar.length()) { - assertTrue(jar + " too small", false); - } - } + for (String s : jars) { + File jar = new File(libDir, "aspectj" + s + ".jar"); + assertTrue(jar.getPath(), jar.canRead()); + if (10 > jar.length()) { + assertTrue(jar + " too small", false); + } + } } /** * Show messages from the task. diff --git a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java index 4926d42e8..e044afc01 100644 --- a/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java +++ b/build/src/test/java/org/aspectj/internal/tools/build/UtilsTest.java @@ -49,21 +49,20 @@ public class UtilsTest extends TestCase { "aspectjrt" }) { void checkOthers(OSGIBundle osgiBundle, StringBuffer sb) { RequiredBundle[] bundles = osgiBundle.getRequiredBundles(); - for (int i = 0; i < bundles.length; i++) { - RequiredBundle bundle = bundles[i]; - if ("aspectjrt".equals(bundle.name)) { - if (!bundle.optional) { - sb - .append("expected required bundle aspectjrt to be optional"); - } - String version = "[1.5.0,1.5.5]"; - if (!(version.equals(bundle.versions))) { - sb.append("expected version " + version - + " got " + bundle.versions - + " for required bundle aspectjrt"); - } - } - } + for (RequiredBundle bundle : bundles) { + if ("aspectjrt".equals(bundle.name)) { + if (!bundle.optional) { + sb + .append("expected required bundle aspectjrt to be optional"); + } + String version = "[1.5.0,1.5.5]"; + if (!(version.equals(bundle.versions))) { + sb.append("expected version " + version + + " got " + bundle.versions + + " for required bundle aspectjrt"); + } + } + } } } }; @@ -140,9 +139,9 @@ public class UtilsTest extends TestCase { /** disabled pending research */ public void skip_testOSGIManifests() throws Exception { StringBuffer sb = new StringBuffer(); - for (int i = 0; i < TESTS.length; i++) { - TESTS[i].run(sb); - } + for (ManifestTest test : TESTS) { + test.run(sb); + } if (0 < sb.length()) { fail(sb.toString()); } diff --git a/loadtime/src/main/java/org/aspectj/weaver/loadtime/Aj.java b/loadtime/src/main/java/org/aspectj/weaver/loadtime/Aj.java index 652ea0932..abd8ecc87 100644 --- a/loadtime/src/main/java/org/aspectj/weaver/loadtime/Aj.java +++ b/loadtime/src/main/java/org/aspectj/weaver/loadtime/Aj.java @@ -199,8 +199,7 @@ public class Aj implements ClassPreProcessor { System.err.println("Weaver adaptors before queue processing:"); Map<AdaptorKey,ExplicitlyInitializedClassLoaderWeavingAdaptor> m = WeaverContainer.weavingAdaptors; Set<AdaptorKey> keys = m.keySet(); - for (Iterator<AdaptorKey> iterator = keys.iterator(); iterator.hasNext();) { - Object object = iterator.next(); + for (Object object : keys) { System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object)); } } @@ -223,8 +222,7 @@ public class Aj implements ClassPreProcessor { System.err.println("Weaver adaptors after queue processing:"); Map<AdaptorKey,ExplicitlyInitializedClassLoaderWeavingAdaptor> m = WeaverContainer.weavingAdaptors; Set<AdaptorKey> keys = m.keySet(); - for (Iterator<AdaptorKey> iterator = keys.iterator(); iterator.hasNext();) { - Object object = iterator.next(); + for (Object object : keys) { System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object)); } } diff --git a/loadtime/src/main/java/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java b/loadtime/src/main/java/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java index 21f81720e..173310591 100644 --- a/loadtime/src/main/java/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java +++ b/loadtime/src/main/java/org/aspectj/weaver/loadtime/ClassLoaderWeavingAdaptor.java @@ -219,8 +219,7 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { */ List<String> getAspectClassNames(List<Definition> definitions) { List<String> aspects = new LinkedList<String>(); - for (Iterator<Definition> it = definitions.iterator(); it.hasNext(); ) { - Definition def = it.next(); + for (Definition def : definitions) { List<String> defAspects = def.getAspectClassNames(); if (defAspects != null) { aspects.addAll(defAspects); @@ -598,9 +597,9 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { String fastMatchInfo = null; for (Definition definition : definitions) { - for (Iterator<String> iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) { + for (String value : definition.getIncludePatterns()) { hasIncludes = true; - String include = iterator1.next(); + String include = value; fastMatchInfo = looksLikeStartsWith(include); if (fastMatchInfo != null) { includeStartsWith.add(fastMatchInfo); @@ -613,9 +612,9 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { includeTypePattern.add(includePattern); } } - for (Iterator<String> iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) { + for (String s : definition.getExcludePatterns()) { hasExcludes = true; - String exclude = iterator1.next(); + String exclude = s; fastMatchInfo = looksLikeStartsWith(exclude); if (fastMatchInfo != null) { excludeStartsWith.add(fastMatchInfo); @@ -628,8 +627,8 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { } else if (exclude .equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) { // TODO need a more sophisticated analysis here, to allow for similar situations - excludeSpecial.add(new String[] { "org.codehaus.groovy.", - "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController" }); + excludeSpecial.add(new String[]{"org.codehaus.groovy.", + "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController"}); // for the related test: // } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) { // excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" }); @@ -737,8 +736,7 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { */ private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) { for (Definition definition : definitions) { - for (Iterator<String> iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) { - String dump = iterator1.next(); + for (String dump : definition.getDumpPatterns()) { TypePattern pattern = new PatternParser(dump).parseTypePattern(); dumpTypePattern.add(pattern); } @@ -828,9 +826,9 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { } } boolean fastAccept = false;// defaults to false if no fast include - for (int i = 0; i < includeStartsWith.size(); i++) { + for (String s : includeStartsWith) { didSomeIncludeMatching = true; - fastAccept = fastClassName.startsWith(includeStartsWith.get(i)); + fastAccept = fastClassName.startsWith(s); if (fastAccept) { return true; } @@ -866,9 +864,9 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { } } } - for (int i = 0; i < includeStartsWith.size(); i++) { + for (String s : includeStartsWith) { didSomeIncludeMatching = true; - boolean fastaccept = fastClassName.startsWith(includeStartsWith.get(i)); + boolean fastaccept = fastClassName.startsWith(s); if (fastaccept) { return true; } @@ -898,14 +896,14 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { // still try to avoid ResolvedType if we have simple patterns // EXCLUDE: if one match then reject String fastClassName = aspectClassName.replace('/', '.').replace('.', '$'); - for (int i = 0; i < aspectExcludeStartsWith.size(); i++) { - if (fastClassName.startsWith(aspectExcludeStartsWith.get(i))) { + for (String value : aspectExcludeStartsWith) { + if (fastClassName.startsWith(value)) { return false; } } // INCLUDE: if one match then accept - for (int i = 0; i < aspectIncludeStartsWith.size(); i++) { - if (fastClassName.startsWith(aspectIncludeStartsWith.get(i))) { + for (String s : aspectIncludeStartsWith) { + if (fastClassName.startsWith(s)) { return true; } } @@ -946,8 +944,7 @@ public class ClassLoaderWeavingAdaptor extends WeavingAdaptor { // TODO AV - optimize for className.startWith only ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true); // dump - for (Iterator<TypePattern> iterator = dumpTypePattern.iterator(); iterator.hasNext();) { - TypePattern typePattern = iterator.next(); + for (TypePattern typePattern : dumpTypePattern) { if (typePattern.matchesStatically(classInfo)) { // dump match return true; diff --git a/loadtime/src/main/java/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java b/loadtime/src/main/java/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java index 15e1e9fd4..6f5b58702 100644 --- a/loadtime/src/main/java/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java +++ b/loadtime/src/main/java/org/aspectj/weaver/loadtime/ConcreteAspectCodeGen.java @@ -173,8 +173,7 @@ public class ConcreteAspectCodeGen { } if (parent.isParameterizedType()) { UnresolvedType[] typeParameters = parent.getTypeParameters(); - for (int i = 0; i < typeParameters.length; i++) { - UnresolvedType typeParameter = typeParameters[i]; + for (UnresolvedType typeParameter : typeParameters) { if (typeParameter instanceof ResolvedType && ((ResolvedType) typeParameter).isMissing()) { reportError("Unablet to resolve type parameter '" + typeParameter.getName() + "' from " + stringify()); return false; @@ -306,8 +305,7 @@ public class ConcreteAspectCodeGen { } ResolvedMember[] rms = type.getDeclaredMethods(); if (rms != null) { - for (int i = 0; i < rms.length; i++) { - ResolvedMember member = rms[i]; + for (ResolvedMember member : rms) { String key = member.getName() + member.getSignature(); if (member.isAbstract()) { collector.put(key, member); @@ -340,8 +338,8 @@ public class ConcreteAspectCodeGen { if (as == null || as.length == 0) { return false; } - for (int i = 0; i < as.length; i++) { - if (as[i].getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) { + for (AnnotationAJ a : as) { + if (a.getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) { return true; } } @@ -438,8 +436,7 @@ public class ConcreteAspectCodeGen { cbody.append(InstructionConstants.RETURN); cg.addMethodGen(init); - for (Iterator<Definition.Pointcut> it = concreteAspect.pointcuts.iterator(); it.hasNext();) { - Definition.Pointcut abstractPc = (Definition.Pointcut) it.next(); + for (Definition.Pointcut abstractPc : concreteAspect.pointcuts) { // TODO AV - respect visibility instead of opening up as public? LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg); SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), abstractPc.expression); @@ -646,113 +643,113 @@ public class ConcreteAspectCodeGen { value = value.substring(equalsIndex+1).trim(); } boolean keyIsOk = false; - for (int m=0;m<rms.length;m++) { + for (ResolvedMember rm : rms) { NameValuePair nvp = null; - if (rms[m].getName().equals(key)) { + if (rm.getName().equals(key)) { // found it! - keyIsOk=true; - UnresolvedType rt = rms[m].getReturnType(); + keyIsOk = true; + UnresolvedType rt = rm.getReturnType(); if (rt.isPrimitiveType()) { switch (rt.getSignature().charAt(0)) { - case 'J': // long - try { - long longValue = Long.parseLong(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_LONG,cp,longValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a long"); - return null; - } - break; - case 'S': // short - try { - short shortValue = Short.parseShort(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_SHORT,cp,shortValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a short"); - return null; - } - break; - case 'F': // float - try { - float floatValue = Float.parseFloat(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT,cp,floatValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a float"); - return null; - } - break; - case 'D': // double - try { - double doubleValue = Double.parseDouble(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE,cp,doubleValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a double"); - return null; - } - break; - case 'I': // integer - try { - int intValue = Integer.parseInt(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_INT,cp,intValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as an integer"); - return null; - } - break; - case 'B': // byte - try { - byte byteValue = Byte.parseByte(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BYTE,cp,byteValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a byte"); - return null; - } - break; - case 'C': // char - if (value.length()<2) { - reportError("unable to interpret annotation value '"+value+"' as a char"); - return null; - } - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_CHAR,cp,value.charAt(1)),cp); - break; - case 'Z': // boolean - try { - boolean booleanValue = Boolean.parseBoolean(value); - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN,cp,booleanValue),cp); - } catch (NumberFormatException nfe) { - reportError("unable to interpret annotation value '"+value+"' as a boolean"); - return null; - } - break; + case 'J': // long + try { + long longValue = Long.parseLong(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_LONG, cp, longValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a long"); + return null; + } + break; + case 'S': // short + try { + short shortValue = Short.parseShort(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_SHORT, cp, shortValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a short"); + return null; + } + break; + case 'F': // float + try { + float floatValue = Float.parseFloat(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT, cp, floatValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a float"); + return null; + } + break; + case 'D': // double + try { + double doubleValue = Double.parseDouble(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE, cp, doubleValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a double"); + return null; + } + break; + case 'I': // integer + try { + int intValue = Integer.parseInt(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_INT, cp, intValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as an integer"); + return null; + } + break; + case 'B': // byte + try { + byte byteValue = Byte.parseByte(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BYTE, cp, byteValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a byte"); + return null; + } + break; + case 'C': // char + if (value.length() < 2) { + reportError("unable to interpret annotation value '" + value + "' as a char"); + return null; + } + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_CHAR, cp, value.charAt(1)), cp); + break; + case 'Z': // boolean + try { + boolean booleanValue = Boolean.parseBoolean(value); + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN, cp, booleanValue), cp); + } catch (NumberFormatException nfe) { + reportError("unable to interpret annotation value '" + value + "' as a boolean"); + return null; + } + break; default: - reportError("not yet supporting XML setting of annotation values of type "+rt.getName()); + reportError("not yet supporting XML setting of annotation values of type " + rt.getName()); return null; } } else if (UnresolvedType.JL_STRING.equals(rt)) { - if (value.length()<2) { - reportError("Invalid string value specified in annotation string: "+annotationString); + if (value.length() < 2) { + reportError("Invalid string value specified in annotation string: " + annotationString); return null; } - value = value.substring(1,value.length()-1); // trim the quotes off - nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.STRING,cp,value),cp); + value = value.substring(1, value.length() - 1); // trim the quotes off + nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.STRING, cp, value), cp); } else if (UnresolvedType.JL_CLASS.equals(rt)) { // format of class string: // Foo.class // java.lang.Foo.class - if (value.length()<6) { - reportError("Not a well formed class value for an annotation '"+value+"'"); + if (value.length() < 6) { + reportError("Not a well formed class value for an annotation '" + value + "'"); return null; } - String clazz = value.substring(0,value.length()-6); - boolean qualified = clazz.indexOf(".")!=-1; + String clazz = value.substring(0, value.length() - 6); + boolean qualified = clazz.indexOf(".") != -1; if (!qualified) { // if not qualified, have to assume java.lang - clazz = "java.lang."+clazz; + clazz = "java.lang." + clazz; } - nvp = new NameValuePair(key,new ClassElementValue(new ObjectType(clazz),cp),cp); + nvp = new NameValuePair(key, new ClassElementValue(new ObjectType(clazz), cp), cp); } } - if (nvp!=null) { + if (nvp != null) { aaj.addElementNameValuePair(nvp); } } @@ -920,9 +917,9 @@ public class ConcreteAspectCodeGen { // Generate code to load the parameters int pos = 1; // first slot after 'this' - for (int i = 0; i < paramTypes.size(); i++) { - adviceBody.append(InstructionFactory.createLoad(paramTypes.get(i), pos)); - pos += paramTypes.get(i).getSize(); + for (Type paramType : paramTypes) { + adviceBody.append(InstructionFactory.createLoad(paramType, pos)); + pos += paramType.getSize(); } // Generate the delegate call diff --git a/loadtime/src/main/java/org/aspectj/weaver/loadtime/Options.java b/loadtime/src/main/java/org/aspectj/weaver/loadtime/Options.java index 4e60c7b86..31b125610 100644 --- a/loadtime/src/main/java/org/aspectj/weaver/loadtime/Options.java +++ b/loadtime/src/main/java/org/aspectj/weaver/loadtime/Options.java @@ -60,8 +60,7 @@ public class Options { Collections.reverse(flags); // do a first round on the message handler since it will report the options themselves - for (Iterator<String> iterator = flags.iterator(); iterator.hasNext();) { - String arg = iterator.next(); + for (String arg : flags) { if (arg.startsWith(OPTIONVALUED_messageHandler)) { if (arg.length() > OPTIONVALUED_messageHandler.length()) { String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim(); @@ -77,8 +76,7 @@ public class Options { } // configure the other options - for (Iterator<String> iterator = flags.iterator(); iterator.hasNext();) { - String arg = iterator.next(); + for (String arg : flags) { if (arg.equals(OPTION_15)) { weaverOption.java5 = true; } else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) { diff --git a/loadtime/src/test/java/org/aspectj/weaver/loadtime/JRockitAgentTest.java b/loadtime/src/test/java/org/aspectj/weaver/loadtime/JRockitAgentTest.java index 1c5a8536c..cd5590914 100644 --- a/loadtime/src/test/java/org/aspectj/weaver/loadtime/JRockitAgentTest.java +++ b/loadtime/src/test/java/org/aspectj/weaver/loadtime/JRockitAgentTest.java @@ -94,9 +94,9 @@ public class JRockitAgentTest extends TestCase { super(clone.getParent()); URL[] urls = clone.getURLs(); - for (int i = 0; i < urls.length; i++) { + for (URL value : urls) { Object pathElement; - URL url = urls[i]; + URL url = value; if (debug) System.out.println("JRockitClassLoader.JRockitClassLoader() url=" + url.getPath()); File file = new File(encode(url.getFile())); diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/AjdtCommand.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/AjdtCommand.java index 27553cf7d..25de41c2d 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/AjdtCommand.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/AjdtCommand.java @@ -44,19 +44,19 @@ public class AjdtCommand implements ICommand { buildManager = new AjBuildManager(handler); savedArgs = new String[args.length]; System.arraycopy(args, 0, savedArgs, 0, savedArgs.length); - for (int i = 0; i < args.length; i++) { + for (String arg : args) { // AMC - PR58681. No need to abort on -help as the Eclipse compiler does the right thing. // if ("-help".equals(args[i])) { // // should be info, but handler usually suppresses // MessageUtil.abort(handler, BuildArgParser.getUsage()); // return true; -// } else - if ("-X".equals(args[i])) { - // should be info, but handler usually suppresses - MessageUtil.abort(handler, BuildArgParser.getXOptionUsage()); - return true; - } - } +// } else + if ("-X".equals(arg)) { + // should be info, but handler usually suppresses + MessageUtil.abort(handler, BuildArgParser.getXOptionUsage()); + return true; + } + } return doCommand(handler, false); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/BuildArgParser.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/BuildArgParser.java index 1b18b980d..57af301f2 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/BuildArgParser.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/BuildArgParser.java @@ -190,8 +190,8 @@ public class BuildArgParser extends Main { } if (buildConfig.getSourceRoots() != null) { - for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext();) { - fileList.addAll(collectSourceRootFiles((File) i.next())); + for (File file : buildConfig.getSourceRoots()) { + fileList.addAll(collectSourceRootFiles(file)); } } @@ -416,8 +416,8 @@ public class BuildArgParser extends Main { if (parser.classpath == null) { addClasspath(System.getProperty("java.class.path", ""), ret); List fixedList = new ArrayList(); - for (Iterator it = ret.iterator(); it.hasNext();) { - String entry = (String) it.next(); + for (Object o : ret) { + String entry = (String) o; if (!entry.endsWith("aspectjtools.jar")) { fixedList.add(entry); } @@ -438,8 +438,8 @@ public class BuildArgParser extends Main { File dirFile = new File(tokenizer.nextToken()); if (dirFile.canRead() && dirFile.isDirectory()) { File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER); - for (int i = 0; i < files.length; i++) { - classpathCollector.add(files[i].getAbsolutePath()); + for (File file : files) { + classpathCollector.add(file.getAbsolutePath()); } } else { // XXX alert on invalid -extdirs entries diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/ConfigParser.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/ConfigParser.java index 1bbd3327b..bdb87cb2b 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/ConfigParser.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/ajc/ConfigParser.java @@ -42,8 +42,8 @@ public class ConfigParser { public void parseCommandLine(String[] argsArray) throws ParseException { location = new CommandLineLocation(); LinkedList<Arg> args = new LinkedList<Arg>(); - for (int i = 0; i < argsArray.length; i++) { - args.add(new Arg(argsArray[i], location)); + for (String s : argsArray) { + args.add(new Arg(s, location)); } String aspectjOptions = null; try { @@ -188,8 +188,8 @@ public class ConfigParser { showWarning("no matching files found in: " + dir); } - for (int i = 0; i < files.length; i++) { - addFile(files[i]); + for (File file : files) { + addFile(file); } } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java index a23eb05f0..e58b57ea7 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjCompilerAdapter.java @@ -180,8 +180,8 @@ public class AjCompilerAdapter extends AbstractCompilerAdapter { try { // not great ... but one more check before we continue, see pr132314 if (!reportedErrors && units != null) { - for (int i = 0; i < units.length; i++) { - if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) { + for (CompilationUnitDeclaration unit : units) { + if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) { reportedErrors = true; break; } @@ -273,8 +273,8 @@ public class AjCompilerAdapter extends AbstractCompilerAdapter { private List getBinarySourcesFrom(Map binarySourceEntries) { // Map is fileName |-> List<UnwovenClassFile> List ret = new ArrayList(); - for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) { - String sourceFileName = (String) binIter.next(); + for (Object o : binarySourceEntries.keySet()) { + String sourceFileName = (String) o; List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName); // XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit" CompilationResult result = new CompilationResult(sourceFileName.toCharArray(), 0, 0, Integer.MAX_VALUE); @@ -286,16 +286,16 @@ public class AjCompilerAdapter extends AbstractCompilerAdapter { } private void notifyRequestor() { - for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { - InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); + for (Object o : resultsPendingWeave) { + InterimCompilationResult iresult = (InterimCompilationResult) o; compiler.requestor.acceptResult(iresult.result().tagAsAccepted()); } } private void weave() throws IOException { // ensure weaver state is set up correctly - for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { - InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); + for (Object o : resultsPendingWeave) { + InterimCompilationResult iresult = (InterimCompilationResult) o; for (int i = 0; i < iresult.unwovenClassFiles().length; i++) { weaver.addClassFile(iresult.unwovenClassFiles()[i], false); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjPipeliningCompilerAdapter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjPipeliningCompilerAdapter.java index 77410281b..6ea878265 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjPipeliningCompilerAdapter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/AjPipeliningCompilerAdapter.java @@ -191,8 +191,8 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { } if (!reportedErrors && units != null) { - for (int i = 0; i < units.length; i++) { - if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) { + for (CompilationUnitDeclaration unit : units) { + if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) { reportedErrors = true; break; // TODO break or exit here? } @@ -202,11 +202,11 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { // Break the units into two lists... List<CompilationUnitDeclaration> aspects = new ArrayList<CompilationUnitDeclaration>(); List<CompilationUnitDeclaration> nonaspects = new ArrayList<CompilationUnitDeclaration>(); - for (int i = 0; i < units.length; i++) { - if (containsAnAspect(units[i])) { - aspects.add(units[i]); + for (CompilationUnitDeclaration unit : units) { + if (containsAnAspect(unit)) { + aspects.add(unit); } else { - nonaspects.add(units[i]); + nonaspects.add(unit); } } @@ -347,8 +347,8 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { int sourceStart = md.sourceStart; int[] separators = md.compilationResult.lineSeparatorPositions; int declarationStartLine = 1; - for (int i = 0; i < separators.length; i++) { - if (sourceStart < separators[i]) { + for (int separator : separators) { + if (sourceStart < separator) { break; } declarationStartLine++; @@ -385,8 +385,8 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { try { // not great ... but one more check before we continue, see pr132314 if (!reportedErrors && units != null) { - for (int i = 0; i < units.length; i++) { - if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) { + for (CompilationUnitDeclaration unit : units) { + if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) { reportedErrors = true; break; } @@ -476,8 +476,7 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { private List<InterimCompilationResult> getBinarySourcesFrom(Map<String, List<UnwovenClassFile>> binarySourceEntries) { // Map is fileName |-> List<UnwovenClassFile> List<InterimCompilationResult> ret = new ArrayList<InterimCompilationResult>(); - for (Iterator<String> binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) { - String sourceFileName = binIter.next(); + for (String sourceFileName : binarySourceEntries.keySet()) { List<UnwovenClassFile> unwovenClassFiles = binarySourceEntries.get(sourceFileName); // XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit" CompilationResult result = new CompilationResult(sourceFileName.toCharArray(), 0, 0, Integer.MAX_VALUE); @@ -489,8 +488,7 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { } private void notifyRequestor() { - for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { - InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); + for (InterimCompilationResult iresult : resultsPendingWeave) { compiler.requestor.acceptResult(iresult.result().tagAsAccepted()); } } @@ -500,8 +498,7 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { if (debugPipeline) { System.err.println(">.weaveQueuedEntries()"); } - for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) { - InterimCompilationResult iresult = (InterimCompilationResult) iter.next(); + for (InterimCompilationResult iresult : resultsPendingWeave) { for (int i = 0; i < iresult.unwovenClassFiles().length; i++) { weaver.addClassFile(iresult.unwovenClassFiles()[i], false); } @@ -602,15 +599,14 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { private boolean containsAnAspect(CompilationUnitDeclaration cud) { TypeDeclaration[] typeDecls = cud.types; if (typeDecls != null) { - for (int i = 0; i < typeDecls.length; i++) { // loop through top level types in the file - TypeDeclaration declaration = typeDecls[i]; + for (TypeDeclaration declaration : typeDecls) { // loop through top level types in the file if (isAspect(declaration)) { return true; } if (declaration.memberTypes != null) { TypeDeclaration[] memberTypes = declaration.memberTypes; - for (int j = 0; j < memberTypes.length; j++) { // loop through inner types - if (containsAnAspect(memberTypes[j])) { + for (TypeDeclaration memberType : memberTypes) { // loop through inner types + if (containsAnAspect(memberType)) { return true; } } @@ -626,8 +622,8 @@ public class AjPipeliningCompilerAdapter extends AbstractCompilerAdapter { } if (tDecl.memberTypes != null) { TypeDeclaration[] memberTypes = tDecl.memberTypes; - for (int j = 0; j < memberTypes.length; j++) { // loop through inner types - if (containsAnAspect(memberTypes[j])) { + for (TypeDeclaration memberType : memberTypes) { // loop through inner types + if (containsAnAspect(memberType)) { return true; } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ClassFileBasedByteCodeProvider.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ClassFileBasedByteCodeProvider.java index dcee93802..77872416a 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ClassFileBasedByteCodeProvider.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ClassFileBasedByteCodeProvider.java @@ -42,13 +42,13 @@ public class ClassFileBasedByteCodeProvider ClassFile[] cfs = result.getClassFiles(); UnwovenClassFile[] ret = new UnwovenClassFile[result.compiledTypes.size()]; int i=0; - for (Iterator iterator = result.compiledTypes.keySet().iterator(); iterator.hasNext();) { - char[] className = (char[])iterator.next(); - ClassFile cf = (ClassFile)result.compiledTypes.get(className); + for (Object o : result.compiledTypes.keySet()) { + char[] className = (char[]) o; + ClassFile cf = (ClassFile) result.compiledTypes.get(className); // OPTIMIZE use char[] for classname ClassFileBasedByteCodeProvider p = new ClassFileBasedByteCodeProvider(cf); String fileName = nameProvider.getOutputClassFileName(cf.fileName(), result); - ret[i++] = new UnwovenClassFileWithThirdPartyManagedBytecode(fileName,new String(className).replace('/','.'),p); + ret[i++] = new UnwovenClassFileWithThirdPartyManagedBytecode(fileName, new String(className).replace('/', '.'), p); } return ret; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/CommonPrinter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/CommonPrinter.java index cfdc9da0a..9ba3a697a 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/CommonPrinter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/CommonPrinter.java @@ -168,8 +168,8 @@ public class CommonPrinter { protected StringBuilder printAnnotations(Annotation[] annotations) { int length = annotations.length; - for (int i = 0; i < length; i++) { - printAnnotation(annotations[i]); + for (Annotation annotation : annotations) { + printAnnotation(annotation); output.append(" "); //$NON-NLS-1$ } return output; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java index ebb82372f..83d528a90 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverAdapter.java @@ -234,8 +234,8 @@ public class WeaverAdapter implements IClassFileProvider, IWeaveRequestor, Itera return true; } char[] victim = null; - for (Iterator iter = aMap.keySet().iterator(); iter.hasNext();) { - char[] thisKey = (char[]) iter.next(); + for (Object o : aMap.keySet()) { + char[] thisKey = (char[]) o; if (CharOperation.equals(thisKey, key)) { // if (skey.equals(new String(thisKey))) { victim = thisKey; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java index 78238afe7..eb5ca53d9 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/WeaverMessageHandler.java @@ -211,10 +211,10 @@ public class WeaverMessageHandler implements IMessageHandler { boolean usedBinarySourceFileName) { List<IProblem> ret = new ArrayList<IProblem>(); - for (int i = 0; i < sourceLocations.size(); i++) { - ISourceLocation loc = (ISourceLocation) sourceLocations.get(i); + for (Object sourceLocation : sourceLocations) { + ISourceLocation loc = (ISourceLocation) sourceLocation; if (loc != null) { - DefaultProblem dp = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[] {}, + DefaultProblem dp = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[]{}, ProblemSeverities.Ignore, getStartPos(loc, null), getEndPos(loc, null), loc.getLine(), loc.getColumn()); ret.add(dp); } else { diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.java index 2d2dd999c..91d998692 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AdviceDeclaration.java @@ -145,8 +145,7 @@ public class AdviceDeclaration extends AjMethodDeclaration { proceedInInners = false; declaredExceptions = new UnresolvedType[0]; - for (int i = 0; i < n; i++) { - Proceed call = proceedCalls.get(i); + for (Proceed call : proceedCalls) { if (call.inInner) { // System.err.println("proceed in inner: " + call); proceedInInners = true; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjConstructorDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjConstructorDeclaration.java index 8e9c04d16..247c7618f 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjConstructorDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjConstructorDeclaration.java @@ -48,8 +48,8 @@ public class AjConstructorDeclaration extends ConstructorDeclaration { int[] separators = compilationResult().lineSeparatorPositions; int declarationStartLine = 1; - for (int i = 0; i < separators.length; i++) { - if (sourceStart < separators[i]) break; + for (int separator : separators) { + if (sourceStart < separator) break; declarationStartLine++; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjMethodDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjMethodDeclaration.java index f2a938c4e..8130d3ef4 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjMethodDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AjMethodDeclaration.java @@ -66,8 +66,8 @@ public class AjMethodDeclaration extends MethodDeclaration { int[] separators = compilationResult().lineSeparatorPositions; int declarationStartLine = 1; - for (int i = 0; i < separators.length; i++) { - if (sourceStart < separators[i]) break; + for (int separator : separators) { + if (sourceStart < separator) break; declarationStartLine++; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java index deea7f3f4..78cca38c0 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/AspectDeclaration.java @@ -317,9 +317,9 @@ public class AspectDeclaration extends TypeDeclaration { } } if (memberTypes != null) { - for (int i = 0; i < memberTypes.length; i++) { - if (memberTypes[i] instanceof IntertypeMemberClassDeclaration) { - IntertypeMemberClassDeclaration itdMemberClassDeclaration = (IntertypeMemberClassDeclaration) memberTypes[i]; + for (TypeDeclaration memberType : memberTypes) { + if (memberType instanceof IntertypeMemberClassDeclaration) { + IntertypeMemberClassDeclaration itdMemberClassDeclaration = (IntertypeMemberClassDeclaration) memberType; AjAttribute attribute = itdMemberClassDeclaration.getAttribute(); if (attribute != null) { classFile.extraAttributes.add(new EclipseAttributeAdapter(attribute)); @@ -340,8 +340,8 @@ public class AspectDeclaration extends TypeDeclaration { */ @SuppressWarnings("unchecked") private void addVersionAttributeIfNecessary(ClassFile classFile) { - for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) { - EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next(); + for (Object o : classFile.extraAttributes) { + EclipseAttributeAdapter element = (EclipseAttributeAdapter) o; if (CharOperation.equals(element.getNameChars(), weaverVersionChars)) { return; } @@ -352,12 +352,10 @@ public class AspectDeclaration extends TypeDeclaration { private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray(); private void generateInlineAccessMembers(ClassFile classFile) { - for (Iterator<SuperAccessMethodPair> i = superAccessForInline.values().iterator(); i.hasNext();) { - AccessForInlineVisitor.SuperAccessMethodPair pair = i.next(); + for (SuperAccessMethodPair pair : superAccessForInline.values()) { generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod); } - for (Iterator<Map.Entry<ResolvedMember, Binding>> i = accessForInline.entrySet().iterator(); i.hasNext();) { - Map.Entry<ResolvedMember, Binding> e = i.next(); + for (Map.Entry<ResolvedMember, Binding> e : accessForInline.entrySet()) { generateInlineAccessMethod(classFile, e.getValue(), e.getKey()); } } @@ -1140,9 +1138,9 @@ public class AspectDeclaration extends TypeDeclaration { public void processIntertypeMemberTypes(ClassScope classScope) { factory = EclipseFactory.fromScopeLookupEnvironment(scope); if (memberTypes != null) { - for (int i = 0; i < memberTypes.length; i++) { - if (memberTypes[i] instanceof IntertypeMemberClassDeclaration) { - EclipseTypeMunger m = ((IntertypeMemberClassDeclaration) memberTypes[i]).build(classScope); + for (TypeDeclaration memberType : memberTypes) { + if (memberType instanceof IntertypeMemberClassDeclaration) { + EclipseTypeMunger m = ((IntertypeMemberClassDeclaration) memberType).build(classScope); if (m != null) { mungeNewInnerClass(m, factory); concreteName.typeMungers.add(m); @@ -1166,14 +1164,14 @@ public class AspectDeclaration extends TypeDeclaration { buildPerClause(scope); if (methods != null) { - for (int i = 0; i < methods.length; i++) { - if (methods[i] instanceof InterTypeDeclaration) { - EclipseTypeMunger m = ((InterTypeDeclaration) methods[i]).build(classScope); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration method : methods) { + if (method instanceof InterTypeDeclaration) { + EclipseTypeMunger m = ((InterTypeDeclaration) method).build(classScope); if (m != null) { concreteName.typeMungers.add(m); } - } else if (methods[i] instanceof DeclareDeclaration) { - Declare d = ((DeclareDeclaration) methods[i]).build(classScope); + } else if (method instanceof DeclareDeclaration) { + Declare d = ((DeclareDeclaration) method).build(classScope); if (d != null) { concreteName.declares.add(d); } @@ -1257,8 +1255,8 @@ public class AspectDeclaration extends TypeDeclaration { // TODO should probably avoid putting it onto BTBs at all (since already there) if (!(targetSourceTypeBinding instanceof BinaryTypeBinding)) { ReferenceBinding[] existingMemberTypes = targetSourceTypeBinding.memberTypes(); - for (int i = 0; i < existingMemberTypes.length; i++) { - char[] compounded = CharOperation.concatWith(existingMemberTypes[i].compoundName, '.'); + for (ReferenceBinding existingMemberType : existingMemberTypes) { + char[] compounded = CharOperation.concatWith(existingMemberType.compoundName, '.'); if (CharOperation.endsWith(compounded, mungerMemberTypeName)) { scope.problemReporter().signalError(sourceStart(), sourceEnd(), "target type already declares a member type with the name '" + munger.getMemberTypeName() + "'"); diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java index fddcc3b90..1afb46a7c 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java @@ -131,12 +131,12 @@ public class InterTypeConstructorDeclaration extends InterTypeDeclaration { private boolean suppressingNoExplicitConstructorCall() { if (this.annotations == null) return false; - for (int i = 0; i < this.annotations.length; i++) { - if (new String(this.annotations[i].resolvedType.signature()).equals(SUPPRESSAJWARNINGS)) { - if (this.annotations[i] instanceof MarkerAnnotation) { + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation : this.annotations) { + if (new String(annotation.resolvedType.signature()).equals(SUPPRESSAJWARNINGS)) { + if (annotation instanceof MarkerAnnotation) { return true; - } else if (this.annotations[i] instanceof SingleMemberAnnotation) { - SingleMemberAnnotation sma = (SingleMemberAnnotation) this.annotations[i]; + } else if (annotation instanceof SingleMemberAnnotation) { + SingleMemberAnnotation sma = (SingleMemberAnnotation) annotation; if (sma.memberValue instanceof ArrayInitializer) { ArrayInitializer memberValue = (ArrayInitializer) sma.memberValue; for (int j = 0; j < memberValue.expressions.length; j++) { diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeDeclaration.java index 89d2482c7..bbff3e136 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeDeclaration.java @@ -358,8 +358,8 @@ public abstract class InterTypeDeclaration extends AjMethodDeclaration { ParameterizedSingleTypeReference paramRef = (ParameterizedSingleTypeReference) onType; TypeReference[] rb = paramRef.typeArguments; typeVariableAliases = new ArrayList(); - for (int i = 0; i < rb.length; i++) { - typeVariableAliases.add(CharOperation.toString(rb[i].getTypeName())); + for (TypeReference typeReference : rb) { + typeVariableAliases.add(CharOperation.toString(typeReference.getTypeName())); } } else if (onType instanceof ParameterizedQualifiedTypeReference) { ParameterizedQualifiedTypeReference paramRef = (ParameterizedQualifiedTypeReference) onType; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.java index 9b6d7ddcc..89e066df5 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeFieldDeclaration.java @@ -341,8 +341,7 @@ public class InterTypeFieldDeclaration extends InterTypeDeclaration { } else { if (!onTypeBinding.isInterface()) { FieldBinding[] existingFields = onTypeBinding.fields(); - for (int f = 0; f < existingFields.length; f++) { - FieldBinding fieldBinding = existingFields[f]; + for (FieldBinding fieldBinding : existingFields) { if (CharOperation.equals(fieldBinding.name, sig.getName().toCharArray())) { fieldMunger.version = NewFieldTypeMunger.VersionOne; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java index 01e975a63..70811e090 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/InterTypeMethodDeclaration.java @@ -162,9 +162,7 @@ public class InterTypeMethodDeclaration extends InterTypeDeclaration { ReferenceBinding supertype = onTypeBinding.superclass(); while (supertype != null && reportError) { MethodBinding[] possibles = supertype.getMethods(declaredSelector); - for (int i = 0; i < possibles.length; i++) { - MethodBinding mb = possibles[i]; - + for (MethodBinding mb : possibles) { boolean couldBeMatch = true; if (mb.parameters.length != realthing.parameters.length) couldBeMatch = false; @@ -290,11 +288,11 @@ public class InterTypeMethodDeclaration extends InterTypeDeclaration { Argument[] itdArgs = this.arguments; if (itdArgs != null) { - for (int a = 0; a < itdArgs.length; a++) { - LocalVariableBinding lvb = itdArgs[a].binding; + for (Argument itdArg : itdArgs) { + LocalVariableBinding lvb = itdArg.binding; LocalVariableBinding lvbCopy = new LocalVariableBinding(lvb.name, lvb.type, lvb.modifiers, true); // e37: have to create a declaration so that the check in ClassFile (line 2538) won't skip it - lvbCopy.declaration = new LocalDeclaration(itdArgs[a].name,0,0); + lvbCopy.declaration = new LocalDeclaration(itdArg.name, 0, 0); codeStream.record(lvbCopy); lvbCopy.recordInitializationStartPC(0); lvbCopy.resolvedPosition = lvb.resolvedPosition; @@ -311,9 +309,9 @@ public class InterTypeMethodDeclaration extends InterTypeDeclaration { codeStream.aload_0(); resolvedPosition = 1; } - for (int i = 0; i < length; i++) { - codeStream.load(parameters[i], resolvedPosition); - if ((parameters[i] == TypeBinding.DOUBLE) || (parameters[i] == TypeBinding.LONG)) + for (TypeBinding parameter : parameters) { + codeStream.load(parameter, resolvedPosition); + if ((parameter == TypeBinding.DOUBLE) || (parameter == TypeBinding.LONG)) resolvedPosition += 2; else resolvedPosition++; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java index 087e87d6c..70a610950 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PointcutDeclaration.java @@ -268,8 +268,8 @@ public class PointcutDeclaration extends AjMethodDeclaration { * is added. So, this method adds the attribute if someone else hasn't already. */ private void addVersionAttributeIfNecessary(ClassFile classFile) { - for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) { - EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next(); + for (Object o : classFile.extraAttributes) { + EclipseAttributeAdapter element = (EclipseAttributeAdapter) o; if (CharOperation.equals(element.getNameChars(), weaverVersionChars)) return; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/Proceed.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/Proceed.java index bd8e4db35..743e8c204 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/Proceed.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/Proceed.java @@ -104,9 +104,9 @@ public class Proceed extends MessageSend { } boolean argsContainCast = false; - for (int i=0; i<arguments.length;i++) { - if (arguments[i] instanceof CastExpression) argsContainCast = true; - // if (arguments[i].constant==null) arguments[i].constant=Constant.NotAConstant; + for (Expression argument : arguments) { + if (argument instanceof CastExpression) argsContainCast = true; + // if (arguments[i].constant==null) arguments[i].constant=Constant.NotAConstant; } // TypeBinding[] argumentTypes = Binding.NO_PARAMETERS; // if (this.arguments != null) { diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PseudoTokens.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PseudoTokens.java index 4777d0faf..8e0f2a635 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PseudoTokens.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/PseudoTokens.java @@ -153,8 +153,8 @@ public class PseudoTokens extends ASTNode { public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) { int counter = 0; // Counter can be used by postParse as a value to compute uniqueness (if required) - for (int i=0, len=tokens.length; i < len; i++) { - counter+=tokens[i].postParse(typeDec, enclosingDec, counter); + for (PseudoToken token : tokens) { + counter += token.postParse(typeDec, enclosingDec, counter); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java index 96f0d3227..79f31f94e 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java @@ -63,9 +63,9 @@ public class SuperFixerVisitor extends ASTVisitor { localTypeDeclaration.binding.modifiers |=Modifier.PUBLIC; MethodBinding[] bindings = localTypeDeclaration.binding.methods; if (bindings!=null) { - for (int i=0,max=bindings.length;i<max;i++) { - if (CharOperation.equals(bindings[i].selector,ctor)) { - bindings[i].modifiers|=Modifier.PUBLIC; + for (MethodBinding binding : bindings) { + if (CharOperation.equals(binding.selector, ctor)) { + binding.modifiers |= Modifier.PUBLIC; } } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java index 90ca34c45..6698787f0 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/ast/ValidateAtAspectJAnnotationsVisitor.java @@ -370,8 +370,8 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { if (arguments == null) { return names; } else { - for (int i = 0; i < arguments.length; i++) { - names.add(new String(arguments[i].name)); + for (Argument argument : arguments) { + names.add(new String(argument.name)); } return names; } @@ -486,10 +486,10 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { MemberValuePair[] mvps = ann.memberValuePairs; if (mvps == null) return null; - for (int i = 0; i < mvps.length; i++) { - if (CharOperation.equals(memberName.toCharArray(), mvps[i].name)) { - if (mvps[i].value instanceof StringLiteral) { - StringLiteral sv = (StringLiteral) mvps[i].value; + for (MemberValuePair mvp : mvps) { + if (CharOperation.equals(memberName.toCharArray(), mvp.name)) { + if (mvp.value instanceof StringLiteral) { + StringLiteral sv = (StringLiteral) mvp.value; location[0] = sv.sourceStart; location[1] = sv.sourceEnd; return new String(sv.source()); @@ -686,45 +686,45 @@ public class ValidateAtAspectJAnnotationsVisitor extends ASTVisitor { public AspectJAnnotations(Annotation[] annotations) { if (annotations == null) return; - for (int i = 0; i < annotations.length; i++) { - if (annotations[i].resolvedType == null) + for (Annotation annotation : annotations) { + if (annotation.resolvedType == null) continue; // user messed up annotation declaration - char[] sig = annotations[i].resolvedType.signature(); + char[] sig = annotation.resolvedType.signature(); if (CharOperation.equals(afterAdviceSig, sig)) { adviceKind = AdviceKind.After; - addAdviceAnnotation(annotations[i]); + addAdviceAnnotation(annotation); } else if (CharOperation.equals(afterReturningAdviceSig, sig)) { adviceKind = AdviceKind.AfterReturning; - addAdviceAnnotation(annotations[i]); + addAdviceAnnotation(annotation); } else if (CharOperation.equals(afterThrowingAdviceSig, sig)) { adviceKind = AdviceKind.AfterThrowing; - addAdviceAnnotation(annotations[i]); + addAdviceAnnotation(annotation); } else if (CharOperation.equals(beforeAdviceSig, sig)) { adviceKind = AdviceKind.Before; - addAdviceAnnotation(annotations[i]); + addAdviceAnnotation(annotation); } else if (CharOperation.equals(aroundAdviceSig, sig)) { adviceKind = AdviceKind.Around; - addAdviceAnnotation(annotations[i]); + addAdviceAnnotation(annotation); } else if (CharOperation.equals(adviceNameSig, sig)) { hasAdviceNameAnnotation = true; - adviceNameAnnotation = annotations[i]; + adviceNameAnnotation = annotation; } else if (CharOperation.equals(declareParentsSig, sig)) { hasDeclareParents = true; } else if (CharOperation.equals(aspectSig, sig)) { if (hasAspectAnnotation) { hasMultipleAspectAnnotations = true; - duplicateAspectAnnotation = annotations[i]; + duplicateAspectAnnotation = annotation; } else { hasAspectAnnotation = true; - aspectAnnotation = annotations[i]; + aspectAnnotation = annotation; } } else if (CharOperation.equals(pointcutSig, sig)) { if (hasPointcutAnnotation) { hasMultiplePointcutAnnotations = true; - duplicatePointcutAnnotation = annotations[i]; + duplicatePointcutAnnotation = annotation; } else { hasPointcutAnnotation = true; - pointcutAnnotation = annotations[i]; + pointcutAnnotation = annotation; } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java index efd1a2ba2..0384617f9 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java @@ -172,12 +172,12 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC // them in the factory for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; - for (int j = 0; j < b.length; j++) { - factory.addSourceTypeBinding(b[j], units[i]); - if (b[j].superclass instanceof MissingTypeBinding) { + for (SourceTypeBinding sourceTypeBinding : b) { + factory.addSourceTypeBinding(sourceTypeBinding, units[i]); + if (sourceTypeBinding.superclass instanceof MissingTypeBinding) { // e37: Undoing the work in ClassScope.connectSuperClass() as it will lead to cascade errors // TODO allow MissingTypeBinding through here and cope with it in all situations later? - b[j].superclass = units[i].scope.getJavaLangObject(); + sourceTypeBinding.superclass = units[i].scope.getJavaLangObject(); } } } @@ -195,8 +195,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; - for (int j = 0; j < stbs.length; j++) { - SourceTypeBinding stb = stbs[j]; + for (SourceTypeBinding stb : stbs) { typesToProcess.add(stb); TypeDeclaration typeDeclaration = stb.scope.referenceContext; if (typeDeclaration instanceof AspectDeclaration) { @@ -255,8 +254,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { CompilationUnitScope cus = units[i].scope; SourceTypeBinding[] stbs = cus.topLevelTypes; - for (int j = 0; j < stbs.length; j++) { - SourceTypeBinding stb = stbs[j]; + for (SourceTypeBinding stb : stbs) { typesToProcess.add(stb); } } @@ -287,20 +285,20 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; - for (int j = 0; j < b.length; j++) { + for (SourceTypeBinding sourceTypeBinding : b) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( - CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName); - resolvePointcutDeclarations(b[j].scope); + CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, sourceTypeBinding.sourceName); + resolvePointcutDeclarations(sourceTypeBinding.scope); CompilationAndWeavingContext.leavingPhase(tok); } } for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) { SourceTypeBinding[] b = units[i].scope.topLevelTypes; - for (int j = 0; j < b.length; j++) { + for (SourceTypeBinding sourceTypeBinding : b) { ContextToken tok = CompilationAndWeavingContext.enteringPhase( - CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName); - addAdviceLikeDeclares(b[j].scope); + CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, sourceTypeBinding.sourceName); + addAdviceLikeDeclares(sourceTypeBinding.scope); CompilationAndWeavingContext.leavingPhase(tok); } } @@ -390,8 +388,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC // now check our membertypes (pr119570) ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - SourceTypeBinding rb = (SourceTypeBinding) memberTypes[i]; + for (ReferenceBinding memberType : memberTypes) { + SourceTypeBinding rb = (SourceTypeBinding) memberType; if (!rb.superclass().equals(sourceType)) { doSupertypesFirst(rb.superclass(), yetToProcess); } @@ -424,16 +422,14 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } // Then look at the superinterface list ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces(); - for (int i = 0; i < interfaceTypes.length; i++) { - ReferenceBinding binding = interfaceTypes[i]; + for (ReferenceBinding binding : interfaceTypes) { if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) { // System.err.println("Recursing to superinterface "+new // String(binding.getFileName())); weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes, mode); - } - else if (binding instanceof ParameterizedTypeBinding && (((ParameterizedTypeBinding)binding).type instanceof SourceTypeBinding) && typesToProcess.contains(((ParameterizedTypeBinding)binding).type)) { - weaveIntertypes(typesToProcess, (SourceTypeBinding) ((ParameterizedTypeBinding)binding).type, typeMungers, declareParents, declareAnnotationOnTypes, mode); + } else if (binding instanceof ParameterizedTypeBinding && (((ParameterizedTypeBinding) binding).type instanceof SourceTypeBinding) && typesToProcess.contains(((ParameterizedTypeBinding) binding).type)) { + weaveIntertypes(typesToProcess, (SourceTypeBinding) ((ParameterizedTypeBinding) binding).type, typeMungers, declareParents, declareAnnotationOnTypes, mode); } } weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false, mode); @@ -460,8 +456,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope); + for (ReferenceBinding memberType : memberTypes) { + addAdviceLikeDeclares(((SourceTypeBinding) memberType).scope); } } @@ -479,8 +475,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC SourceTypeBinding sourceType = s.referenceContext.binding; ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope); + for (ReferenceBinding memberType : memberTypes) { + addCrosscuttingStructures(((SourceTypeBinding) memberType).scope); } } @@ -491,14 +487,14 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC AbstractMethodDeclaration[] methods = dec.methods; boolean initializedMethods = false; if (methods != null) { - for (int i = 0; i < methods.length; i++) { - if (methods[i] instanceof PointcutDeclaration) { + for (AbstractMethodDeclaration method : methods) { + if (method instanceof PointcutDeclaration) { hasPointcuts = true; if (!initializedMethods) { sourceType.methods(); // force initialization initializedMethods = true; } - ((PointcutDeclaration) methods[i]).resolvePointcut(s); + ((PointcutDeclaration) method).resolvePointcut(s); } } } @@ -510,8 +506,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope); + for (ReferenceBinding memberType : memberTypes) { + resolvePointcutDeclarations(((SourceTypeBinding) memberType).scope); } } @@ -567,8 +563,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC System.err.println("Unexpectedly found null for memberTypes of " + sourceType.debugName()); } if (memberTypes != null) { - for (int i = 0, length = memberTypes.length; i < length; i++) { - buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope); + for (ReferenceBinding memberType : memberTypes) { + buildInterTypeAndPerClause(((SourceTypeBinding) memberType).scope); } } } @@ -713,8 +709,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC // Check if the type we are looking at is the topMostImplementor of a // dangerous interface - // report a problem if it is. - for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); + for (Object o : dangerousInterfaces.entrySet()) { + Map.Entry entry = (Map.Entry) o; ResolvedType interfaceType = (ResolvedType) entry.getKey(); if (onType.isTopmostImplementor(interfaceType)) { factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null); @@ -804,8 +800,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } } if (mode == 0 || mode == 2) { - for (Iterator<ConcreteTypeMunger> i = typeMungers.iterator(); i.hasNext();) { - EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); + for (ConcreteTypeMunger typeMunger : typeMungers) { + EclipseTypeMunger munger = (EclipseTypeMunger) typeMunger; if (munger.matches(onType)) { // if (needOldStyleWarning) { // factory.showMessage(IMessage.WARNING, "The class for " + onType @@ -827,8 +823,8 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } onType.checkInterTypeMungers(); - for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) { - EclipseTypeMunger munger = (EclipseTypeMunger) i.next(); + for (ConcreteTypeMunger concreteTypeMunger : onType.getInterTypeMungers()) { + EclipseTypeMunger munger = (EclipseTypeMunger) concreteTypeMunger; if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) { if (munger.munge(sourceType, onType)) { if (factory.pushinCollector != null) { @@ -860,9 +856,9 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC } ReferenceBinding[] memberTypes = sourceType.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - if (memberTypes[i] instanceof SourceTypeBinding) { - weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents, + for (ReferenceBinding memberType : memberTypes) { + if (memberType instanceof SourceTypeBinding) { + weaveInterTypeDeclarations((SourceTypeBinding) memberType, typeMungers, declareParents, declareAnnotationOnTypes, false, mode); } } @@ -878,8 +874,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) { List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType); - for (Iterator<ConcreteTypeMunger> i = previouslyAppliedMungers.iterator(); i.hasNext();) { - ConcreteTypeMunger m = i.next(); + for (ConcreteTypeMunger m : previouslyAppliedMungers) { EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m); if (munger.munge(sourceType, onType)) { if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) { @@ -899,8 +894,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC ResolvedType resolvedSourceType = factory.fromEclipse(sourceType); List<ResolvedType> newParents = declareParents.findMatchingNewParents(resolvedSourceType, false); if (!newParents.isEmpty()) { - for (Iterator<ResolvedType> i = newParents.iterator(); i.hasNext();) { - ResolvedType parent = i.next(); + for (ResolvedType parent : newParents) { if (dangerousInterfaces.containsKey(parent)) { ResolvedType onType = factory.fromEclipse(sourceType); factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent), @@ -1128,8 +1122,7 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations; if (currentAnnotations != null) { - for (int i = 0; i < currentAnnotations.length; i++) { - Annotation annotation = currentAnnotations[i]; + for (Annotation annotation : currentAnnotations) { String a = CharOperation.toString(annotation.type.getTypeName()); String b = CharOperation.toString(toAdd[0].type.getTypeName()); // FIXME asc we have a lint for attempting to add an annotation @@ -1209,9 +1202,9 @@ public class AjLookupEnvironment extends LookupEnvironment implements AnonymousC ResolvedMember[] methods = rt.getDeclaredMethods(); ResolvedMember decaMethod = null; String nameToLookFor = decA.getAnnotationMethod(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(nameToLookFor)) { - decaMethod = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals(nameToLookFor)) { + decaMethod = method; break; } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java index a520124da..3d2fb727f 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseAnnotationConvertor.java @@ -73,14 +73,13 @@ public class EclipseAnnotationConvertor { MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; if (memberValuePairs != null) { int memberValuePairsLength = memberValuePairs.length; - for (int i = 0; i < memberValuePairsLength; i++) { - MemberValuePair memberValuePair = memberValuePairs[i]; + for (MemberValuePair memberValuePair : memberValuePairs) { MethodBinding methodBinding = memberValuePair.binding; if (methodBinding == null) { // is this just a marker annotation? throw new MissingImplementationException( "Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation - + "]"); + + "]"); } else { AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType); AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av); diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java index 47357df67..6e9fafff9 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseFactory.java @@ -654,8 +654,8 @@ public class EclipseFactory { } UnresolvedType[] typeArguments = typeX.getTypeParameters(); if (typeArguments != null) { - for (int i = 0; i < typeArguments.length; i++) { - if (typeArguments[i].isTypeVariableReference()) { + for (UnresolvedType typeArgument : typeArguments) { + if (typeArgument.isTypeVariableReference()) { return true; } } @@ -1177,8 +1177,8 @@ public class EclipseFactory { } ReferenceBinding[] memberTypes = binding.memberTypes; - for (int i = 0, length = memberTypes.length; i < length; i++) { - addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit); + for (ReferenceBinding memberType : memberTypes) { + addSourceTypeBinding((SourceTypeBinding) memberType, unit); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java index ecd4f3ddd..3fa41b1ea 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseResolvedMember.java @@ -80,8 +80,7 @@ public class EclipseResolvedMember extends ResolvedMemberImpl { if (annotationTypes == null) { return false; } - for (int i = 0; i < annotationTypes.length; i++) { - ResolvedType type = annotationTypes[i]; + for (ResolvedType type : annotationTypes) { if (type.equals(ofType)) { return true; } @@ -126,8 +125,7 @@ public class EclipseResolvedMember extends ResolvedMemberImpl { if (annos == null) { return null; } - for (int i = 0; i < annos.length; i++) { - Annotation anno = annos[i]; + for (Annotation anno : annos) { UnresolvedType ut = UnresolvedType.forSignature(new String(anno.resolvedType.signature())); if (w.resolve(ut).equals(ofType)) { // Found the one @@ -335,10 +333,9 @@ public class EclipseResolvedMember extends ResolvedMemberImpl { // Grab the set of bindings with matching selector MethodBinding[] mb = ((MethodBinding) realBinding).declaringClass.getMethods(methodBinding.selector); if (mb != null) { - for (int m = 0, max = mb.length; m < max; m++) { - MethodBinding candidate = mb[m]; + for (MethodBinding candidate : mb) { if (candidate instanceof InterTypeMethodBinding) { - if (InterTypeMemberFinder.matches(mb[m], methodBinding)) { + if (InterTypeMemberFinder.matches(candidate, methodBinding)) { InterTypeMethodBinding intertypeMethodBinding = (InterTypeMethodBinding) candidate; Annotation[] annos = intertypeMethodBinding.sourceMethod.annotations; return annos; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseScope.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseScope.java index 2b3467ea3..26c260628 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseScope.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseScope.java @@ -181,8 +181,7 @@ public class EclipseScope implements IScope { } ImportBinding[] imports = cuScope.imports; - for (int i = 0; i < imports.length; i++) { - ImportBinding importBinding = imports[i]; + for (ImportBinding importBinding : imports) { String importName = new String(CharOperation.concatWith(importBinding.compoundName, '.')); // XXX wrong behavior for java.util.Map.* @@ -194,8 +193,8 @@ public class EclipseScope implements IScope { } TypeBinding[] topTypes = cuScope.topLevelTypes; - for (int i = 0; i < topTypes.length; i++) { - importedNamesList.add(world.fromBinding(topTypes[i]).getName()); + for (TypeBinding topType : topTypes) { + importedNamesList.add(world.fromBinding(topType).getName()); } importedNames = importedNamesList.toArray(new String[importedNamesList.size()]); @@ -211,8 +210,8 @@ public class EclipseScope implements IScope { addClassAndParentsToPrefixes(binding.superclass(), importedPrefixesList); ReferenceBinding[] superinterfaces = binding.superInterfaces(); if (superinterfaces != null) { - for (int i = 0; i < superinterfaces.length; i++) { - addClassAndParentsToPrefixes(superinterfaces[i], importedPrefixesList); + for (ReferenceBinding superinterface : superinterfaces) { + addClassAndParentsToPrefixes(superinterface, importedPrefixesList); } } } @@ -233,9 +232,9 @@ public class EclipseScope implements IScope { // XXX add good errors when would bind to extra parameters @Override public FormalBinding lookupFormal(String name) { - for (int i = 0, len = bindings.length; i < len; i++) { - if (bindings[i].getName().equals(name)) - return bindings[i]; + for (FormalBinding binding : bindings) { + if (binding.getName().equals(name)) + return binding; } return null; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java index 349758e36..efd4fb0db 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseSourceType.java @@ -176,8 +176,8 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { return false; } ResolvedType[] annotations = getAnnotationTypes(); - for (int i = 0; i < annotations.length; i++) { - if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) { + for (ResolvedType annotation : annotations) { + if ("org.aspectj.lang.annotation.Aspect".equals(annotation.getName())) { return true; } } @@ -190,19 +190,19 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { if (ans == null) { return ""; } - for (int i = 0; i < ans.length; i++) { - if (ans[i].resolvedType == null) { + for (Annotation an : ans) { + if (an.resolvedType == null) { continue; // XXX happens if we do this very early from } // buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect - char[] sig = ans[i].resolvedType.signature(); + char[] sig = an.resolvedType.signature(); if (CharOperation.equals(pointcutSig, sig)) { - if (ans[i].memberValuePairs().length == 0) { + if (an.memberValuePairs().length == 0) { return ""; // empty pointcut expression } - Expression expr = ans[i].memberValuePairs()[0].value; + Expression expr = an.memberValuePairs()[0].value; if (expr instanceof StringLiteral) { StringLiteral sLit = ((StringLiteral) expr); return new String(sLit.source()); @@ -223,14 +223,14 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { if (annotations == null) { return false; } - for (int i = 0; i < annotations.length; i++) { - if (annotations[i].resolvedType == null) { + for (Annotation annotation : annotations) { + if (annotation.resolvedType == null) { continue; // XXX happens if we do this very early from } // buildInterTypeandPerClause // may prevent us from resolving references made in @Pointcuts to // an @Pointcut in a code-style aspect - char[] sig = annotations[i].resolvedType.signature(); + char[] sig = annotation.resolvedType.signature(); if (CharOperation.equals(pointcutSig, sig)) { return true; } @@ -266,8 +266,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { // sure bindings are completed AbstractMethodDeclaration[] methods = declaration.methods; if (methods != null) { - for (int i = 0, len = methods.length; i < len; i++) { - AbstractMethodDeclaration amd = methods[i]; + for (AbstractMethodDeclaration amd : methods) { if (amd == null || amd.ignoreFurtherInvestigation) { continue; } @@ -326,16 +325,15 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { if (isEnum()) { // The bindings for the eclipse binding will include values/valueof - for (int m=0,len=ms.length;m<len;m++) { - MethodBinding mb = ms[m]; + for (MethodBinding mb : ms) { if ((mb instanceof SyntheticMethodBinding) && mb.isStatic()) { // cannot use .isSynthetic() because it isn't truly synthetic - if (CharOperation.equals(mb.selector,valuesCharArray) && mb.parameters.length==0 && mb.returnType.isArrayType() && ((ArrayBinding)mb.returnType).leafComponentType()==binding) { + if (CharOperation.equals(mb.selector, valuesCharArray) && mb.parameters.length == 0 && mb.returnType.isArrayType() && ((ArrayBinding) mb.returnType).leafComponentType() == binding) { // static <EnumType>[] values() ResolvedMember valuesMember = factory.makeResolvedMember(mb); valuesMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); valuesMember.setPosition(0, 0); declaredMethods.add(valuesMember); - } else if (CharOperation.equals(mb.selector,valueOfCharArray) && mb.parameters.length==1 && CharOperation.equals(mb.parameters[0].signature(),jlString) && mb.returnType==binding) { + } else if (CharOperation.equals(mb.selector, valueOfCharArray) && mb.parameters.length == 1 && CharOperation.equals(mb.parameters[0].signature(), jlString) && mb.returnType == binding) { // static <EnumType> valueOf(String) ResolvedMember valueOfMember = factory.makeResolvedMember(mb); valueOfMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0)); @@ -347,8 +345,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { } FieldBinding[] fields = binding.fields(); - for (int i = 0, len = fields.length; i < len; i++) { - FieldBinding f = fields[i]; + for (FieldBinding f : fields) { declaredFields.add(factory.makeResolvedMember(f)); } @@ -677,8 +674,8 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { @Override public boolean hasAnnotation(UnresolvedType ofType) { ensureAnnotationTypesResolved(); - for (int a = 0, max = annotationTypes.length; a < max; a++) { - if (ofType.equals(annotationTypes[a])) { + for (ResolvedType annotationType : annotationTypes) { + if (ofType.equals(annotationType)) { return true; } } @@ -763,8 +760,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs; if (memberValuePairs != null) { int memberValuePairsLength = memberValuePairs.length; - for (int i = 0; i < memberValuePairsLength; i++) { - MemberValuePair memberValuePair = memberValuePairs[i]; + for (MemberValuePair memberValuePair : memberValuePairs) { MethodBinding methodBinding = memberValuePair.binding; if (methodBinding == null) { // is this just a marker annotation? @@ -947,8 +943,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { ajAnnotationType.isAnnotationWithRuntimeRetention()); MemberValuePair[] pairs = normalAnnotation.memberValuePairs; if (pairs != null) { - for (int p = 0; p < pairs.length; p++) { - MemberValuePair pair = pairs[p]; + for (MemberValuePair pair : pairs) { Expression valueEx = pair.value; AnnotationValue pairValue = null; if (valueEx instanceof Literal) { @@ -1068,8 +1063,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { // Can happen if an aspect is extending a regular class return null; } - for (int i = 0; i < annotations.length; i++) { - Annotation annotation = annotations[i]; + for (Annotation annotation : annotations) { if (annotation != null && annotation.resolvedType != null && CharOperation.equals(aspectSig, annotation.resolvedType.signature())) { // found @Aspect(...) @@ -1092,7 +1086,7 @@ public class EclipseSourceType extends AbstractReferenceTypeDelegate { // safe // ? return determinePerClause(typeDeclaration, clause); - } else if (annotation instanceof NormalAnnotation) { + } else if (annotation instanceof NormalAnnotation) { // this kind if it was added by the visitor! // it is an @Aspect(...something...) NormalAnnotation theAnnotation = (NormalAnnotation) annotation; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java index 4fbdfa849..0a26fafd9 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/EclipseTypeMunger.java @@ -209,18 +209,17 @@ public class EclipseTypeMunger extends ConcreteTypeMunger { MethodBinding binding = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases()); findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding); TypeVariableBinding[] typeVariables = binding.typeVariables; - for (int i = 0; i < typeVariables.length; i++) { - TypeVariableBinding tv = typeVariables[i]; + for (TypeVariableBinding tv : typeVariables) { String name = new String(tv.sourceName); TypeVariableBinding[] tv2 = sourceMethod.binding.typeVariables; - for (int j = 0; j < tv2.length; j++) { - if (new String(tv2[j].sourceName).equals(name)) { - typeVariables[i].declaringElement = binding; + for (TypeVariableBinding typeVariableBinding : tv2) { + if (new String(typeVariableBinding.sourceName).equals(name)) { + tv.declaringElement = binding; } } } - for (int i = 0; i < typeVariables.length; i++) { - if (typeVariables[i].declaringElement == null) { + for (TypeVariableBinding typeVariable : typeVariables) { + if (typeVariable.declaringElement == null) { throw new RuntimeException("Declaring element not set"); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.java index 8b4a917f8..d3e449534 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMemberFinder.java @@ -53,8 +53,7 @@ public class InterTypeMemberFinder implements IMemberFinder { } int fieldLength = fieldName.length; - for (int i = 0, len = interTypeFields.size(); i < len; i++) { - FieldBinding field = interTypeFields.get(i); + for (FieldBinding field : interTypeFields) { if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) { retField = resolveConflicts(sourceTypeBinding, retField, field, site, scope); } @@ -256,15 +255,14 @@ public class InterTypeMemberFinder implements IMemberFinder { // if (interTypeMethods.isEmpty()) return orig; List<MethodBinding> ret = new ArrayList<MethodBinding>(Arrays.asList(orig)); - for (int i = 0, len = interTypeMethods.size(); i < len; i++) { - MethodBinding method = interTypeMethods.get(i); + for (MethodBinding method : interTypeMethods) { ret.add(method); } ReferenceBinding[] interfaces = sourceTypeBinding.superInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - if (interfaces[i] instanceof SourceTypeBinding) { - SourceTypeBinding intSTB = (SourceTypeBinding) interfaces[i]; + for (ReferenceBinding anInterface : interfaces) { + if (anInterface instanceof SourceTypeBinding) { + SourceTypeBinding intSTB = (SourceTypeBinding) anInterface; addPublicITDSFrom(intSTB, ret); } } @@ -304,9 +302,7 @@ public class InterTypeMemberFinder implements IMemberFinder { Set<MethodBinding> ret = new HashSet<MethodBinding>(Arrays.asList(orig)); // System.err.println("declared method: " + ret + " inters = " + interTypeMethods); - for (int i = 0, len = interTypeMethods.size(); i < len; i++) { - MethodBinding method = interTypeMethods.get(i); - + for (MethodBinding method : interTypeMethods) { if (CharOperation.equals(selector, method.selector)) { ret.add(method); } @@ -341,8 +337,7 @@ public class InterTypeMemberFinder implements IMemberFinder { MethodBinding ret = sourceTypeBinding.getExactMethodBase(selector, argumentTypes, refScope); // An intertype declaration may override an inherited member (Bug#50776) - for (int i = 0, len = interTypeMethods.size(); i < len; i++) { - MethodBinding im = interTypeMethods.get(i); + for (MethodBinding im : interTypeMethods) { if (matches(im, selector, argumentTypes)) { return im; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java index 10e93ae00..213c41d40 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java @@ -61,11 +61,11 @@ public class InterTypeMethodBinding extends MethodBinding { // Ok, we need to set the typevariable declaring elements // 1st set: // If the typevariable is one declared on the source method, then we know we are the declaring element - for (int i = 0; i < typeVariables.length; i++) { - typeVariables[i].declaringElement = this; + for (org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding variable : typeVariables) { + variable.declaringElement = this; } - for (int i = 0; i < typeVariables.length; i++) { - if (typeVariables[i].declaringElement == null) + for (org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding typeVariable : typeVariables) { + if (typeVariable.declaringElement == null) throw new RuntimeException("Declaring element not set"); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedHandler.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedHandler.java index c4c7e1f84..a361cd881 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedHandler.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/lookup/PrivilegedHandler.java @@ -144,8 +144,8 @@ public class PrivilegedHandler implements IPrivilegedHandler { int len = m.size(); ResolvedMember[] ret = new ResolvedMember[len]; int index = 0; - for (Iterator i = m.iterator(); i.hasNext();) { - ret[index++] = (ResolvedMember) i.next(); + for (Object o : m) { + ret[index++] = (ResolvedMember) o; } return ret; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java index c80bbb5e9..ec5a2a545 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/compiler/problem/AjProblemReporter.java @@ -229,8 +229,7 @@ public class AjProblemReporter extends ProblemReporter { // so we don't have to worry about interfaces, just the superclass. onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass); } - for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { - ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); + for (ConcreteTypeMunger m : onTypeX.getInterTypeMungersIncludingSupers()) { ResolvedMember sig = m.getSignature(); if (!Modifier.isAbstract(sig.getModifiers())) { if (ResolvedType.matches( @@ -434,9 +433,8 @@ public class AjProblemReporter extends ProblemReporter { ResolvedType supertypeToLookAt = onTypeX.getSuperclass(); while (supertypeToLookAt != null) { List<ConcreteTypeMunger> itMungers = supertypeToLookAt.getInterTypeMungers(); - for (Iterator<ConcreteTypeMunger> i = itMungers.iterator(); i.hasNext();) { - ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); - if (m.getMunger()!=null && m.getMunger().getKind()== ResolvedTypeMunger.PrivilegedAccess) { + for (ConcreteTypeMunger m : itMungers) { + if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { continue; } ResolvedMember sig = m.getSignature(); @@ -492,13 +490,11 @@ public class AjProblemReporter extends ProblemReporter { AspectDeclaration ad = (AspectDeclaration) typeDecl.enclosingType; if (ad.concreteName != null) { List<Declare> declares = ad.concreteName.declares; - for (Iterator<Declare> iter = declares.iterator(); iter.hasNext();) { - Object dec = iter.next(); + for (Object dec : declares) { if (dec instanceof DeclareParents) { DeclareParents decp = (DeclareParents) dec; TypePattern[] newparents = decp.getParents().getTypePatterns(); - for (int i = 0; i < newparents.length; i++) { - TypePattern pattern = newparents[i]; + for (TypePattern pattern : newparents) { UnresolvedType ut = pattern.getExactType(); if (ut == null) continue; @@ -552,8 +548,7 @@ public class AjProblemReporter extends ProblemReporter { weaverType = factory.fromEclipse(type.superclass()); } Set checked = new HashSet(); - for (Iterator i = weaverType.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) { - ConcreteTypeMunger m = (ConcreteTypeMunger) i.next(); + for (ConcreteTypeMunger m : weaverType.getInterTypeMungersIncludingSupers()) { ResolvedType theAspect = m.getAspectType(); if (!checked.contains(theAspect)) { TypeBinding tb = factory.makeTypeBinding(m.getAspectType()); @@ -570,8 +565,8 @@ public class AjProblemReporter extends ProblemReporter { Collection/* ResolvedMember */privvies = ((ReferenceType) theAspect).getPrivilegedAccesses(); // On an incremental compile the information is in the bcel delegate if (privvies != null) { - for (Iterator iterator = privvies.iterator(); iterator.hasNext();) { - ResolvedMember priv = (ResolvedMember) iterator.next(); + for (Object privvy : privvies) { + ResolvedMember priv = (ResolvedMember) privvy; if (priv.getName().equals(fname)) { return; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java index 1b6343fef..219f2fd48 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java @@ -324,12 +324,11 @@ public class AjBuildConfig implements CompilerConfigurationChangeFlags { return pathname.getPath().endsWith(".class"); } }; - for (Iterator<File> iter = inPath.iterator(); iter.hasNext();) { - File inpathElement = iter.next(); + for (File inpathElement : inPath) { if (inpathElement.isDirectory()) { File[] files = FileUtil.listFiles(inpathElement, filter); - for (int i = 0; i < files.length; i++) { - binaryFiles.add(new BinarySourceFile(inpathElement, files[i])); + for (File file : files) { + binaryFiles.add(new BinarySourceFile(inpathElement, file)); } } } @@ -537,8 +536,7 @@ public class AjBuildConfig implements CompilerConfigurationChangeFlags { @SuppressWarnings({ "rawtypes", "unchecked" }) void join(Collection local, Collection global) { - for (Iterator iter = global.iterator(); iter.hasNext();) { - Object next = iter.next(); + for (Object next : global) { if (!local.contains(next)) { local.add(next); } @@ -955,8 +953,8 @@ public class AjBuildConfig implements CompilerConfigurationChangeFlags { allPaths = FileSystem.ClasspathNormalizer.normalize(allPaths); this.checkedClasspaths = new FileSystem.Classpath[allPaths.size()]; allPaths.toArray(this.checkedClasspaths); - for (int i=0;i<checkedClasspaths.length;i++) { - if (checkedClasspaths[i] == null) { + for (Classpath checkedClasspath : checkedClasspaths) { + if (checkedClasspath == null) { throw new IllegalStateException(); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java index aacda594c..98c115190 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjBuildManager.java @@ -453,26 +453,24 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour private void copyResourcesToDestination() throws IOException { // resources that we need to copy are contained in the injars and inpath only - for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) { - File inJar = (File) i.next(); - copyResourcesFromJarFile(inJar); - } - - for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) { - File inPathElement = (File) i.next(); - if (inPathElement.isDirectory()) { - copyResourcesFromDirectory(inPathElement); - } else { - copyResourcesFromJarFile(inPathElement); - } - } + for (File inJar : buildConfig.getInJars()) { + copyResourcesFromJarFile(inJar); + } + + for (File inPathElement : buildConfig.getInpath()) { + if (inPathElement.isDirectory()) { + copyResourcesFromDirectory(inPathElement); + } + else { + copyResourcesFromJarFile(inPathElement); + } + } if (buildConfig.getSourcePathResources() != null) { - for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) { - String resource = (String) i.next(); - File from = buildConfig.getSourcePathResources().get(resource); - copyResourcesFromFile(from, resource, from); - } + for (String resource : buildConfig.getSourcePathResources().keySet()) { + File from = buildConfig.getSourcePathResources().get(resource); + copyResourcesFromFile(from, resource, from); + } } writeManifest(); @@ -520,12 +518,12 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour }); // For each file, add it either as a real .class file or as a resource - for (int i = 0; i < files.length; i++) { - // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() - // or we are in trouble... - String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); - copyResourcesFromFile(files[i], filename, dir); - } + for (File file : files) { + // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath() + // or we are in trouble... + String filename = file.getAbsolutePath().substring(dir.getAbsolutePath().length() + 1); + copyResourcesFromFile(file, filename, dir); + } } private void copyResourcesFromFile(File f, String filename, File src) throws IOException { @@ -663,28 +661,28 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour Map<File, List<String>> outputDirsAndAspects = findOutputDirsForAspects(); Set<Map.Entry<File, List<String>>> outputDirs = outputDirsAndAspects.entrySet(); - for (Iterator<Map.Entry<File, List<String>>> iterator = outputDirs.iterator(); iterator.hasNext();) { - Map.Entry<File, List<String>> entry = iterator.next(); - File outputDir = entry.getKey(); - List<String> aspects = entry.getValue(); - ByteArrayOutputStream baos = getOutxmlContents(aspects); - if (zos != null) { - ZipEntry newEntry = new ZipEntry(filename); - - zos.putNextEntry(newEntry); - zos.write(baos.toByteArray()); - zos.closeEntry(); - } else { - File outputFile = new File(outputDir, filename); - OutputStream fos = FileUtil.makeOutputStream(outputFile); - fos.write(baos.toByteArray()); - fos.close(); - if (buildConfig.getCompilationResultDestinationManager() != null) { - buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(), - CompilationResultDestinationManager.FILETYPE_RESOURCE); - } - } - } + for (Map.Entry<File, List<String>> entry : outputDirs) { + File outputDir = entry.getKey(); + List<String> aspects = entry.getValue(); + ByteArrayOutputStream baos = getOutxmlContents(aspects); + if (zos != null) { + ZipEntry newEntry = new ZipEntry(filename); + + zos.putNextEntry(newEntry); + zos.write(baos.toByteArray()); + zos.closeEntry(); + } + else { + File outputFile = new File(outputDir, filename); + OutputStream fos = FileUtil.makeOutputStream(outputFile); + fos.write(baos.toByteArray()); + fos.close(); + if (buildConfig.getCompilationResultDestinationManager() != null) { + buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(), + CompilationResultDestinationManager.FILETYPE_RESOURCE); + } + } + } } private ByteArrayOutputStream getOutxmlContents(List aspectNames) { @@ -693,10 +691,10 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour ps.println("<aspectj>"); ps.println("<aspects>"); if (aspectNames != null) { - for (Iterator i = aspectNames.iterator(); i.hasNext();) { - String name = (String) i.next(); - ps.println("<aspect name=\"" + name + "\"/>"); - } + for (Object aspectName : aspectNames) { + String name = (String) aspectName; + ps.println("<aspect name=\"" + name + "\"/>"); + } } ps.println("</aspects>"); ps.println("</aspectj>"); @@ -729,23 +727,22 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour outputDirsToAspects.put(outputDir, aspectNames); } else { List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations(); - for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { - File outputDir = (File) iterator.next(); - outputDirsToAspects.put(outputDir, new ArrayList<String>()); - } + for (Object dir : outputDirs) { + File outputDir = (File) dir; + outputDirsToAspects.put(outputDir, new ArrayList<String>()); + } if (aspectNamesToFileNames != null) { Set<Map.Entry<String, char[]>> entrySet = aspectNamesToFileNames.entrySet(); - for (Iterator<Map.Entry<String, char[]>> iterator = entrySet.iterator(); iterator.hasNext();) { - Map.Entry<String, char[]> entry = iterator.next(); - String aspectName = entry.getKey(); - char[] fileName = entry.getValue(); - File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( - new File(new String(fileName))); - if (!outputDirsToAspects.containsKey(outputDir)) { - outputDirsToAspects.put(outputDir, new ArrayList<String>()); - } - ((List) outputDirsToAspects.get(outputDir)).add(aspectName); - } + for (Map.Entry<String, char[]> entry : entrySet) { + String aspectName = entry.getKey(); + char[] fileName = entry.getValue(); + File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass( + new File(new String(fileName))); + if (!outputDirsToAspects.containsKey(outputDir)) { + outputDirsToAspects.put(outputDir, new ArrayList<String>()); + } + ((List) outputDirsToAspects.get(outputDir)).add(aspectName); + } } } return outputDirsToAspects; @@ -904,12 +901,12 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour // (they are like 'source' files then), and enables a cleaner incremental treatment of // class file changes in indirs. File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter); - for (int j = 0; j < binSrcs.length; j++) { - UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir); - List<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>(); - ucfl.add(ucf); - state.recordBinarySource(binSrcs[j].getPath(), ucfl); - } + for (File binSrc : binSrcs) { + UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrc, inPathElement, outputDir); + List<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>(); + ucfl.add(ucf); + state.recordBinarySource(binSrc.getPath(), ucfl); + } } } @@ -1034,10 +1031,9 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour // Translate from strings to File objects String[] filenames = new String[files.size()]; int idx = 0; - for (Iterator<File> fIterator = files.iterator(); fIterator.hasNext();) { - File f = fIterator.next(); - filenames[idx++] = f.getPath(); - } + for (File f : files) { + filenames[idx++] = f.getPath(); + } environment = state.getNameEnvironment(); @@ -1154,48 +1150,48 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour if (!hasErrors || proceedOnError()) { Collection<ClassFile> classFiles = unitResult.compiledTypes.values(); boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null); - for (Iterator<ClassFile> iter = classFiles.iterator(); iter.hasNext();) { - ClassFile classFile = iter.next(); - String filename = new String(classFile.fileName()); - String classname = filename.replace('/', '.'); - filename = filename.replace('/', File.separatorChar) + ".class"; - - try { - if (buildConfig.getOutputJar() == null) { - String outfile = writeDirectoryEntry(unitResult, classFile, filename); - getWorld().classWriteEvent(classFile.getCompoundName()); - if (environmentSupportsIncrementalCompilation) { - if (!classname.endsWith("$ajcMightHaveAspect")) { - ResolvedType type = getBcelWorld().resolve(classname); - if (type.isAspect()) { - state.recordAspectClassFile(outfile); - } - } - } - } else { - writeZipEntry(classFile, filename); - } - if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) { - addAspectName(classname, unitResult.getFileName()); - } - } catch (IOException ex) { - IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName), - CANT_WRITE_RESULT, ex); - handler.handleMessage(message); - } - - } + for (ClassFile classFile : classFiles) { + String filename = new String(classFile.fileName()); + String classname = filename.replace('/', '.'); + filename = filename.replace('/', File.separatorChar) + ".class"; + + try { + if (buildConfig.getOutputJar() == null) { + String outfile = writeDirectoryEntry(unitResult, classFile, filename); + getWorld().classWriteEvent(classFile.getCompoundName()); + if (environmentSupportsIncrementalCompilation) { + if (!classname.endsWith("$ajcMightHaveAspect")) { + ResolvedType type = getBcelWorld().resolve(classname); + if (type.isAspect()) { + state.recordAspectClassFile(outfile); + } + } + } + } + else { + writeZipEntry(classFile, filename); + } + if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) { + addAspectName(classname, unitResult.getFileName()); + } + } catch (IOException ex) { + IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName), + CANT_WRITE_RESULT, ex); + handler.handleMessage(message); + } + + } state.noteNewResult(unitResult); unitResult.compiledTypes.clear(); // free up references to AjClassFile instances } if (unitResult.hasProblems() || unitResult.hasTasks()) { IProblem[] problems = unitResult.getAllProblems(); - for (int i = 0; i < problems.length; i++) { - IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld(), - progressListener); - handler.handleMessage(message); - } + for (IProblem problem : problems) { + IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problem, getBcelWorld(), + progressListener); + handler.handleMessage(message); + } } } @@ -1314,14 +1310,15 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour } StringBuffer buf = new StringBuffer(); boolean first = true; - for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { - if (first) { - first = false; - } else { - buf.append(File.pathSeparator); - } - buf.append(it.next().toString()); - } + for (String s : buildConfig.getFullClasspath()) { + if (first) { + first = false; + } + else { + buf.append(File.pathSeparator); + } + buf.append(s.toString()); + } return buf.toString(); } @@ -1349,47 +1346,50 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour } String ret = null; - for (Iterator<String> it = buildConfig.getFullClasspath().iterator(); it.hasNext();) { - File p = new File(it.next()); - // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar - if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { - - try { - String version = null; - Manifest manifest = new JarFile(p).getManifest(); - if (manifest == null) { - ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.getText(); - continue; - } - Attributes attr = manifest.getAttributes("org/aspectj/lang/"); - if (null != attr) { - version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); - if (null != version) { - version = version.trim(); - } - } - // assume that users of development aspectjrt.jar know what they're doing - if (version != null && (Version.DEVELOPMENT.equals(version) || version.endsWith("BUILD-SNAPSHOT"))) { - // MessageUtil.info(holder, - // "running with development version of aspectjrt.jar in " + - // p.getAbsolutePath()); - return null; - } else if (!Version.getText().equals(version)) { - ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.getText() + " found " - + version; - continue; - } - } catch (IOException ioe) { - ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; - } - return null; // this is the "OK" return value! - } else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) { - // likely to be a variant from the springsource bundle repo b272591 - return null; - } else { - // might want to catch other classpath errors - } - } + for (String s : buildConfig.getFullClasspath()) { + File p = new File(s); + // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar + if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) { + + try { + String version = null; + Manifest manifest = new JarFile(p).getManifest(); + if (manifest == null) { + ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.getText(); + continue; + } + Attributes attr = manifest.getAttributes("org/aspectj/lang/"); + if (null != attr) { + version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); + if (null != version) { + version = version.trim(); + } + } + // assume that users of development aspectjrt.jar know what they're doing + if (version != null && (Version.DEVELOPMENT.equals(version) || version.endsWith("BUILD-SNAPSHOT"))) { + // MessageUtil.info(holder, + // "running with development version of aspectjrt.jar in " + + // p.getAbsolutePath()); + return null; + } + else if (!Version.getText().equals(version)) { + ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.getText() + " found " + + version; + continue; + } + } catch (IOException ioe) { + ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe; + } + return null; // this is the "OK" return value! + } + else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) { + // likely to be a variant from the springsource bundle repo b272591 + return null; + } + else { + // might want to catch other classpath errors + } + } if (ret != null) { return ret; // last error found in potentially matching jars... @@ -1547,10 +1547,10 @@ public class AjBuildManager implements IOutputClassFileNameProvider, IBinarySour AjBuildConfig config = (AjBuildConfig) data; List classpath = config.getClasspath(); sb.append("with classpath: "); - for (Iterator iter = classpath.iterator(); iter.hasNext();) { - sb.append(iter.next().toString()); - sb.append(File.pathSeparator); - } + for (Object o : classpath) { + sb.append(o.toString()); + sb.append(File.pathSeparator); + } return sb.toString(); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjState.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjState.java index 30bc1165b..833ce2382 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjState.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AjState.java @@ -384,8 +384,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (modifiedFiles == null) { // do not know, so need to go looking // not our job to account for new and deleted files - for (Iterator<File> i = buildConfig.getFiles().iterator(); i.hasNext();) { - File file = i.next(); + for (File file : buildConfig.getFiles()) { if (!file.exists()) { continue; } @@ -411,8 +410,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe Collection<BinarySourceFile> getModifiedBinaryFiles(long lastBuildTime) { List<BinarySourceFile> ret = new ArrayList<BinarySourceFile>(); // not our job to account for new and deleted files - for (Iterator<BinarySourceFile> i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) { - AjBuildConfig.BinarySourceFile bsfile = i.next(); + for (BinarySourceFile bsfile : buildConfig.getBinaryFiles()) { File file = bsfile.binSrc; if (!file.exists()) { continue; @@ -490,8 +488,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe List<File> classFiles = FileUtil.listClassFiles(dir); - for (Iterator<File> iterator = classFiles.iterator(); iterator.hasNext();) { - File classFile = iterator.next(); + for (File classFile : classFiles) { if (CHECK_STATE_FIRST && state != null) { // Next section reworked based on bug 270033: // if it is an aspect we may or may not be in trouble depending on whether (a) we depend on it (b) it is on the @@ -763,8 +760,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true); } int newlyAffectedFiles = 0; - for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) { - Map.Entry<File, ReferenceCollection> entry = i.next(); + for (Map.Entry<File, ReferenceCollection> entry : references.entrySet()) { ReferenceCollection refs = entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { if (listenerDefined()) { @@ -838,8 +834,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe */ private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) { Set<Map.Entry<String, Long>> entries = structuralChangesSinceLastFullBuild.entrySet(); - for (Iterator<Map.Entry<String, Long>> iterator = entries.iterator(); iterator.hasNext();) { - Map.Entry<String, Long> entry = iterator.next(); + for (Map.Entry<String, Long> entry : entries) { Long l = entry.getValue(); if (l != null) { long lvalue = l.longValue(); @@ -905,8 +900,8 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe // are also capturing project dependencies - when a project we depend on is rebuilt, we can just check // it as a standalone element on our classpath rather than going through them all List<String> modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents(); - for (Iterator<String> iterator = modifiedCpElements.iterator(); iterator.hasNext();) { - File cpElement = new File(iterator.next()); + for (String modifiedCpElement : modifiedCpElements) { + File cpElement = new File(modifiedCpElement); if (cpElement.exists() && !cpElement.isDirectory()) { if (cpElement.lastModified() > lastSuccessfulBuildTime) { return true; @@ -941,8 +936,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe } if (config.getCompilationResultDestinationManager() != null) { List<File> dirs = config.getCompilationResultDestinationManager().getAllOutputLocations(); - for (Iterator<File> iterator = dirs.iterator(); iterator.hasNext();) { - File f = iterator.next(); + for (File f : dirs) { try { File cf = f.getCanonicalFile(); if (!outputLocs.contains(cf)) { @@ -1093,8 +1087,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe // } if (addedFiles != null) { - for (Iterator<File> fIter = addedFiles.iterator(); fIter.hasNext();) { - File o = fIter.next(); + for (File o : addedFiles) { // TODO isn't it a set?? why do this if (!thisTime.contains(o)) { thisTime.add(o); @@ -1132,8 +1125,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe List<BinarySourceFile> addedOrModified = new ArrayList<BinarySourceFile>(); addedOrModified.addAll(addedBinaryFiles); addedOrModified.addAll(getModifiedBinaryFiles()); - for (Iterator<BinarySourceFile> iter = addedOrModified.iterator(); iter.hasNext();) { - AjBuildConfig.BinarySourceFile bsf = iter.next(); + for (BinarySourceFile bsf : addedOrModified) { UnwovenClassFile ucf = createUnwovenClassFile(bsf); if (ucf == null) { continue; @@ -1159,19 +1151,16 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe */ private void removeAllResultsOfLastBuild() { // remove all binarySourceFiles, and all classesFromName... - for (Iterator<List<ClassFile>> iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) { - List<ClassFile> cfs = iter.next(); + for (List<ClassFile> cfs : this.inputClassFilesBySource.values()) { for (ClassFile cf : cfs) { cf.deleteFromFileSystem(buildConfig); } } - for (Iterator<File> iterator = classesFromName.values().iterator(); iterator.hasNext();) { - File f = iterator.next(); + for (File f : classesFromName.values()) { new ClassFile("", f).deleteFromFileSystem(buildConfig); } Set<Map.Entry<String, File>> resourceEntries = resources.entrySet(); - for (Iterator<Map.Entry<String, File>> iter = resourceEntries.iterator(); iter.hasNext();) { - Map.Entry<String, File> resourcePair = iter.next(); + for (Map.Entry<String, File> resourcePair : resourceEntries) { File sourcePath = resourcePair.getValue(); File outputLoc = getOutputLocationFor(buildConfig, sourcePath); if (outputLoc != null) { @@ -1210,8 +1199,8 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe // range of bsf is ucfs, domain is files (.class and jars) in inpath/jars for (BinarySourceFile deletedFile : deletedBinaryFiles) { List<ClassFile> cfs = this.inputClassFilesBySource.get(deletedFile.binSrc.getPath()); - for (Iterator<ClassFile> iterator = cfs.iterator(); iterator.hasNext();) { - deleteClassFile(iterator.next()); + for (ClassFile cf : cfs) { + deleteClassFile(cf); } this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath()); } @@ -1328,14 +1317,14 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences,cr.rootReferences)); UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles(); - for (int i = 0; i < unwovenClassFiles.length; i++) { - File lastTimeRound = classesFromName.get(unwovenClassFiles[i].getClassName()); - recordClassFile(unwovenClassFiles[i], lastTimeRound); - String name = unwovenClassFiles[i].getClassName(); + for (UnwovenClassFile unwovenClassFile : unwovenClassFiles) { + File lastTimeRound = classesFromName.get(unwovenClassFile.getClassName()); + recordClassFile(unwovenClassFile, lastTimeRound); + String name = unwovenClassFile.getClassName(); if (lastTimeRound == null) { deltaAddedClasses.add(name); } - classesFromName.put(name, new File(unwovenClassFiles[i].getFilename())); + classesFromName.put(name, new File(unwovenClassFile.getFilename())); } // need to do this before types are deleted from the World... @@ -1383,10 +1372,10 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe List<ClassFile> classFiles = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile); if (classFiles != null) { - for (int i = 0; i < unwovenClassFiles.length; i++) { + for (UnwovenClassFile unwovenClassFile : unwovenClassFiles) { // deleting also deletes types from the weaver... don't do this if they are // still present this time around... - removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles); + removeFromClassFilesIfPresent(unwovenClassFile.getClassName(), classFiles); } for (ClassFile cf : classFiles) { recordTypeChanged(cf.fullyQualifiedTypeName); @@ -1420,8 +1409,8 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) { List<ClassFile> classFiles = new ArrayList<ClassFile>(); UnwovenClassFile[] types = icr.unwovenClassFiles(); - for (int i = 0; i < types.length; i++) { - classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename()))); + for (UnwovenClassFile type : types) { + classFiles.add(new ClassFile(type.getClassName(), new File(type.getFilename()))); } this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles); } @@ -1438,8 +1427,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (cr != null) { Map compiledTypes = cr.compiledTypes; if (compiledTypes != null) { - for (Iterator<char[]> iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) { - char[] className = iterator.next(); + for (char[] className : (Iterable<char[]>) compiledTypes.keySet()) { String typeName = new String(className).replace('/', '.'); if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) { ResolvedType rt = world.resolve(typeName); @@ -1623,9 +1611,10 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (existingIfs.length != newIfsAsChars.length) { return true; } - new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) { - for (int j = 0; j < existingIfs.length; j++) { - if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) { + new_interface_loop: + for (char[] newIfsAsChar : newIfsAsChars) { + for (char[] existingIf : existingIfs) { + if (CharOperation.equals(existingIf, newIfsAsChar)) { continue new_interface_loop; } } @@ -1654,12 +1643,12 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (newFields.length != existingFs.length) { return true; } - new_field_loop: for (int i = 0; i < newFields.length; i++) { - IBinaryField field = newFields[i]; + new_field_loop: + for (IBinaryField field : newFields) { char[] fieldName = field.getName(); - for (int j = 0; j < existingFs.length; j++) { - if (CharOperation.equals(existingFs[j].getName(), fieldName)) { - IBinaryField existing = existingFs[j]; + for (IBinaryField existingF : existingFs) { + if (CharOperation.equals(existingF.getName(), fieldName)) { + IBinaryField existing = existingF; if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) { return true; } @@ -1732,13 +1721,13 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (newMethods.length != existingMs.length) { return true; } - new_method_loop: for (int i = 0; i < newMethods.length; i++) { - IBinaryMethod method = newMethods[i]; + new_method_loop: + for (IBinaryMethod method : newMethods) { char[] methodName = method.getSelector(); - for (int j = 0; j < existingMs.length; j++) { - if (CharOperation.equals(existingMs[j].getSelector(), methodName)) { + for (IBinaryMethod existingM : existingMs) { + if (CharOperation.equals(existingM.getSelector(), methodName)) { // candidate match - if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) { + if (!CharOperation.equals(method.getMethodDescriptor(), existingM.getMethodDescriptor())) { // ok, the descriptors don't match, but is this a funky ctor on a non-static inner // type? // boolean mightBeOK = @@ -1762,7 +1751,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe continue; // might be overloading } else { // matching sigs - IBinaryMethod existing = existingMs[j]; + IBinaryMethod existing = existingM; if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) { return true; } @@ -1880,13 +1869,14 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe if (existingIfs.length != newIfsAsChars.length) { return true; } - new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) { - for (int j = 0; j < existingIfs.length; j++) { - if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) { + new_interface_loop: + for (char[] newIfsAsChar : newIfsAsChars) { + for (char[] existingIf : existingIfs) { + if (CharOperation.equals(existingIf, newIfsAsChar)) { continue new_interface_loop; } } - logAnalysis(filename,"set of interfaces changed. old="+stringify(existingIfs)+" new="+stringify(newIfsAsChars)); + logAnalysis(filename, "set of interfaces changed. old=" + stringify(existingIfs) + " new=" + stringify(newIfsAsChars)); return true; } @@ -1913,32 +1903,32 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe logAnalysis(filename,"number of fields changed. old="+stringify(existingFs)+" new="+stringify(newFields)); return true; } - new_field_loop: for (int i = 0; i < newFields.length; i++) { - IBinaryField field = newFields[i]; + new_field_loop: + for (IBinaryField field : newFields) { char[] fieldName = field.getName(); - for (int j = 0; j < existingFs.length; j++) { - if (CharOperation.equals(existingFs[j].getName(), fieldName)) { - IBinaryField existing = existingFs[j]; + for (IBinaryField existingF : existingFs) { + if (CharOperation.equals(existingF.getName(), fieldName)) { + IBinaryField existing = existingF; if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) { - logAnalysis(filename,"field modifiers changed '"+existing+"' old=0x"+Integer.toHexString(existing.getModifiers())+" new=0x"+Integer.toHexString(field.getModifiers())); + logAnalysis(filename, "field modifiers changed '" + existing + "' old=0x" + Integer.toHexString(existing.getModifiers()) + " new=0x" + Integer.toHexString(field.getModifiers())); return true; } if (!CharOperation.equals(existing.getTypeName(), field.getTypeName())) { - logAnalysis(filename,"field type changed '"+existing+"' old="+new String(existing.getTypeName())+" new="+new String(field.getTypeName())); + logAnalysis(filename, "field type changed '" + existing + "' old=" + new String(existing.getTypeName()) + " new=" + new String(field.getTypeName())); return true; } char[] existingGSig = existing.getGenericSignature(); char[] fieldGSig = field.getGenericSignature(); if ((existingGSig == null && fieldGSig != null) || (existingGSig != null && fieldGSig == null)) { - logAnalysis(filename,"field generic sig changed '"+existing+"' old="+ - (existingGSig==null?"null":new String(existingGSig))+" new="+(fieldGSig==null?"null":new String(fieldGSig))); + logAnalysis(filename, "field generic sig changed '" + existing + "' old=" + + (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (fieldGSig == null ? "null" : new String(fieldGSig))); return true; } if (existingGSig != null) { if (!CharOperation.equals(existingGSig, fieldGSig)) { - logAnalysis(filename,"field generic sig changed '"+existing+"' old="+ - (existingGSig==null?"null":new String(existingGSig))+" new="+(fieldGSig==null?"null":new String(fieldGSig))); + logAnalysis(filename, "field generic sig changed '" + existing + "' old=" + + (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (fieldGSig == null ? "null" : new String(fieldGSig))); return true; } } @@ -1946,7 +1936,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe continue new_field_loop; } } - logAnalysis(filename,"field changed. New field detected '"+field+"'"); + logAnalysis(filename, "field changed. New field detected '" + field + "'"); return true; } @@ -1999,13 +1989,13 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe logAnalysis(filename,"number of methods changed. old="+stringify(existingMs)+" new="+stringify(newMethods)); return true; } - new_method_loop: for (int i = 0; i < newMethods.length; i++) { - IBinaryMethod method = newMethods[i]; + new_method_loop: + for (IBinaryMethod method : newMethods) { char[] methodName = method.getSelector(); - for (int j = 0; j < existingMs.length; j++) { - if (CharOperation.equals(existingMs[j].getSelector(), methodName)) { + for (IBinaryMethod existingM : existingMs) { + if (CharOperation.equals(existingM.getSelector(), methodName)) { // candidate match - if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) { + if (!CharOperation.equals(method.getMethodDescriptor(), existingM.getMethodDescriptor())) { // ok, the descriptors don't match, but is this a funky ctor on a non-static inner // type? // boolean mightBeOK = @@ -2029,28 +2019,28 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe continue; // might be overloading } else { // matching sigs - IBinaryMethod existing = existingMs[j]; + IBinaryMethod existing = existingM; if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) { - logAnalysis(filename,"method modifiers changed '"+existing+"' old=0x"+Integer.toHexString(existing.getModifiers())+" new=0x"+Integer.toHexString(method.getModifiers())); + logAnalysis(filename, "method modifiers changed '" + existing + "' old=0x" + Integer.toHexString(existing.getModifiers()) + " new=0x" + Integer.toHexString(method.getModifiers())); return true; } if (exceptionClausesDiffer(existing, method)) { - logAnalysis(filename,"method exception clauses changed '"+existing+"' old="+existing+" new="+method); + logAnalysis(filename, "method exception clauses changed '" + existing + "' old=" + existing + " new=" + method); return true; } char[] existingGSig = existing.getGenericSignature(); char[] methodGSig = method.getGenericSignature(); if ((existingGSig == null && methodGSig != null) || (existingGSig != null && methodGSig == null)) { - logAnalysis(filename,"method generic sig changed '"+existing+"' old="+ - (existingGSig==null?"null":new String(existingGSig))+" new="+(methodGSig==null?"null":new String(methodGSig))); + logAnalysis(filename, "method generic sig changed '" + existing + "' old=" + + (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (methodGSig == null ? "null" : new String(methodGSig))); return true; } if (existingGSig != null) { if (!CharOperation.equals(existingGSig, methodGSig)) { - logAnalysis(filename,"method generic sig changed '"+existing+"' old="+ - (existingGSig==null?"null":new String(existingGSig))+" new="+(methodGSig==null?"null":new String(methodGSig))); + logAnalysis(filename, "method generic sig changed '" + existing + "' old=" + + (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (methodGSig == null ? "null" : new String(methodGSig))); return true; } } @@ -2061,7 +2051,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe // TODO missing a return true here? Meaning we have a field in the new that we can't find in the old! } - logAnalysis(filename,"method changed. New method detected '"+stringify(method)+"' (might be a rename)"); + logAnalysis(filename, "method changed. New method detected '" + stringify(method) + "' (might be a rename)"); return true; // (no match found) } @@ -2236,8 +2226,7 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe // System.err.println("simple: " + simpleStrings); // System.err.println("qualif: " + qualifiedStrings); - for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) { - Map.Entry<File, ReferenceCollection> entry = i.next(); + for (Map.Entry<File, ReferenceCollection> entry : references.entrySet()) { ReferenceCollection refs = entry.getValue(); if (refs != null && refs.includes(qualifiedNames, simpleNames)) { File file = entry.getKey(); @@ -2473,10 +2462,10 @@ public class AjState implements CompilerConfigurationChangeFlags, TypeDelegateRe } }); if (weaverGenerated != null) { - for (int i = 0; i < weaverGenerated.length; i++) { - weaverGenerated[i].delete(); + for (File file : weaverGenerated) { + file.delete(); if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) { - buildConfig.getCompilationResultDestinationManager().reportFileRemove(weaverGenerated[i].getPath(), + buildConfig.getCompilationResultDestinationManager().reportFileRemove(file.getPath(), CompilationResultDestinationManager.FILETYPE_CLASS); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java index 450ffc40b..77862dddf 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmElementFormatter.java @@ -321,8 +321,7 @@ public class AsmElementFormatter { TypeReference[] typeRefs = pstr.typeArguments; if (typeRefs != null && typeRefs.length > 0) { handleSig.append("\\<"); - for (int i = 0; i < typeRefs.length; i++) { - TypeReference typeR = typeRefs[i]; + for (TypeReference typeR : typeRefs) { TypeBinding typeB = typeR.resolvedType; if (typeB == null) { typeB = typeR.resolveType(scope); @@ -368,8 +367,7 @@ public class AsmElementFormatter { TypeReference[] typeRefs = pstr.typeArguments[i]; if (typeRefs != null && typeRefs.length > 0) { handleSig.append("\\<"); - for (int j = 0; j < typeRefs.length; j++) { - TypeReference typeR = typeRefs[j]; + for (TypeReference typeR : typeRefs) { TypeBinding typeB = typeR.resolvedType; if (typeB == null) { typeB = typeR.resolveType(scope); @@ -428,11 +426,11 @@ public class AsmElementFormatter { List<char[]> paramSigs = new ArrayList<char[]>(); List<String> paramSourceRefs = new ArrayList<String>(); boolean problemWithSourceRefs = false; - for (int i = 0; i < argArray.length; i++) { - String argName = new String(argArray[i].name); + for (Argument argument : argArray) { + String argName = new String(argument.name); // String argType = "<UnknownType>"; // pr135052 - if (acceptArgument(argName, argArray[i].type.toString())) { - TypeReference typeR = argArray[i].type; + if (acceptArgument(argName, argument.type.toString())) { + TypeReference typeR = argument.type; if (typeR != null && md.scope != null) { TypeBinding typeB = typeR.resolvedType; if (typeB == null) { diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java index 7da62b87c..7ee6cf9e4 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/AsmHierarchyBuilder.java @@ -208,8 +208,7 @@ public class AsmHierarchyBuilder extends ASTVisitor { // Check if already there IProgramElement sourceFolderNode = null; List<IProgramElement> kids = root.getChildren(); - for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) { - IProgramElement child = (IProgramElement) iterator.next(); + for (IProgramElement child : kids) { if (child.getKind() == IProgramElement.Kind.SOURCE_FOLDER && child.getName().equals(sourceFolder)) { sourceFolderNode = child; break; @@ -265,8 +264,7 @@ public class AsmHierarchyBuilder extends ASTVisitor { IProgramElement pkgNode = null; if (structureModel != null && structureModel.getHierarchy().getRoot() != null && rootForSource.getChildren() != null) { - for (Iterator<IProgramElement> it = rootForSource.getChildren().iterator(); it.hasNext();) { - IProgramElement currNode = (IProgramElement) it.next(); + for (IProgramElement currNode : rootForSource.getChildren()) { if (pkgName.equals(currNode.getName())) { pkgNode = currNode; break; @@ -641,9 +639,9 @@ public class AsmHierarchyBuilder extends ASTVisitor { } ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts(); if (members != null) { - for (int i = 0; i < members.length; i++) { - if (members[i].getName().equals(rp.name)) { - return members[i]; + for (ResolvedMember member : members) { + if (member.getName().equals(rp.name)) { + return member; } } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java index 7c92b223e..8a3acaec8 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseAdapterUtils.java @@ -137,15 +137,15 @@ public class EclipseAdapterUtils { // If the user has turned off classfile line number gen, then we may not be able to tell them // about all secondary locations (pr209372) int validPlaces = 0; - for (int ii = 0; ii < seeAlso.length; ii++) { - if (seeAlso[ii].getSourceLineNumber() >= 0) + for (IProblem value : seeAlso) { + if (value.getSourceLineNumber() >= 0) validPlaces++; } ISourceLocation[] seeAlsoLocations = new ISourceLocation[validPlaces]; int pos = 0; - for (int i = 0; i < seeAlso.length; i++) { - if (seeAlso[i].getSourceLineNumber() >= 0) { - seeAlsoLocations[pos++] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i] + for (IProblem iProblem : seeAlso) { + if (iProblem.getSourceLineNumber() >= 0) { + seeAlsoLocations[pos++] = new SourceLocation(new File(new String(iProblem.getOriginatingFileName())), iProblem .getSourceLineNumber()); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.java index f92d37877..31471ad6d 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EclipseSourceContext.java @@ -80,15 +80,14 @@ public class EclipseSourceContext implements IEclipseSourceContext { if (result == null) return; IProblem[] probs = result.getProblems(); if (probs!=null) { - for (int i = 0; i < probs.length; i++) { - IProblem problem = probs[i]; + for (IProblem problem : probs) { if (problem == null) continue; - if (problem.getID() == IProblem.UnusedMethodDeclaredThrownException + if (problem.getID() == IProblem.UnusedMethodDeclaredThrownException || problem.getID() == IProblem.UnusedConstructorDeclaredThrownException) { if (problem.getSourceLineNumber() == problemLineNumber) { - UnusedDeclaredThrownExceptionFilter filter = - new UnusedDeclaredThrownExceptionFilter(problem); - result.removeProblems(filter); + UnusedDeclaredThrownExceptionFilter filter = + new UnusedDeclaredThrownExceptionFilter(problem); + result.removeProblems(filter); } } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EmacsStructureModelManager.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EmacsStructureModelManager.java index 3322ac308..abd1bf5a6 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EmacsStructureModelManager.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/EmacsStructureModelManager.java @@ -42,8 +42,8 @@ public class EmacsStructureModelManager { try { // Set fileSet = StructureModelManager.INSTANCE.getStructureModel().getFileMap().entrySet(); Set fileSet = model.getHierarchy().getFileMapEntrySet(); - for (Iterator it = fileSet.iterator(); it.hasNext();) { - IProgramElement peNode = (IProgramElement) ((Map.Entry) it.next()).getValue(); + for (Object o : fileSet) { + IProgramElement peNode = (IProgramElement) ((Map.Entry) o).getValue(); dumpStructureToFile(peNode); } } catch (IOException ioe) { @@ -95,9 +95,8 @@ public class EmacsStructureModelManager { private void printDecls(IProgramElement node) { print("("); - for (Iterator it = node.getChildren().iterator(); it.hasNext();) { + for (Object nodeObject : node.getChildren()) { // this ignores relations on the compile unit - Object nodeObject = it.next(); // throw new RuntimeException("unimplemented"); // if (nodeObject instanceof IProgramElement) { IProgramElement child = (IProgramElement) nodeObject; diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/IncrementalStateManager.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/IncrementalStateManager.java index e255761b6..aeac71571 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/IncrementalStateManager.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/ajdt/internal/core/builder/IncrementalStateManager.java @@ -55,8 +55,7 @@ public class IncrementalStateManager { public static void persist() { // check serialization works Set<Map.Entry<String, AjState>> entries = incrementalStates.entrySet(); - for (Iterator<Map.Entry<String, AjState>> iterator = entries.iterator(); iterator.hasNext();) { - Map.Entry<String, AjState> entry = iterator.next(); + for (Map.Entry<String, AjState> entry : entries) { System.out.println("Name " + entry.getKey()); File f = new File("n:/temp/foo.ajstate"); try { @@ -77,8 +76,7 @@ public class IncrementalStateManager { } public static void clearIncrementalStates() { - for (Iterator iter = incrementalStates.values().iterator(); iter.hasNext();) { - AjState element = (AjState) iter.next(); + for (AjState element : incrementalStates.values()) { element.wipeAllKnowledge(); } incrementalStates.clear(); @@ -101,8 +99,7 @@ public class IncrementalStateManager { System.err.println("> findStateManagingOutputLocation(" + location + ") has " + allStates.size() + " states to look through"); } - for (Iterator<AjState> iter = allStates.iterator(); iter.hasNext();) { - AjState element = iter.next(); + for (AjState element : allStates) { AjBuildConfig ajbc = element.getBuildConfig(); if (ajbc == null) { // FIXME asc why can it ever be null? @@ -121,8 +118,8 @@ public class IncrementalStateManager { CompilationResultDestinationManager outputManager = ajbc.getCompilationResultDestinationManager(); if (outputManager != null) { List outputDirs = outputManager.getAllOutputLocations(); - for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) { - File dir = (File) iterator.next(); + for (Object o : outputDirs) { + File dir = (File) o; if (dir.equals(location)) { if (debugIncrementalStates) { System.err.println("< findStateManagingOutputLocation(" + location + ") returning " + element); diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java index 6580a388c..57602a440 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjASTConverter.java @@ -107,8 +107,8 @@ public class AjASTConverter extends ASTConverter { adviceDecl.setFlags(adviceDecl.getFlags() | ASTNode.MALFORMED); break; case AST.JLS3: - for (int i = 0, max = typeParameters.length; i < max; i++) { - ((AroundAdviceDeclaration) adviceDecl).typeParameters().add(convert(typeParameters[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) { + ((AroundAdviceDeclaration) adviceDecl).typeParameters().add(convert(typeParameter)); } } } @@ -119,15 +119,15 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference[] thrownExceptions = adviceDeclaration.thrownExceptions; if (thrownExceptions != null) { int thrownExceptionsLength = thrownExceptions.length; - for (int i = 0; i < thrownExceptionsLength; i++) { - adviceDecl.thrownExceptions().add(convert(thrownExceptions[i])); + for (TypeReference thrownException : thrownExceptions) { + adviceDecl.thrownExceptions().add(convert(thrownException)); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = adviceDeclaration.arguments; if (parameters != null) { int parametersLength = parameters.length; - for (int i = 0; i < parametersLength; i++) { - adviceDecl.parameters().add(convert(parameters[i])); + for (Argument parameter : parameters) { + adviceDecl.parameters().add(convert(parameter)); } } int start = adviceDeclaration.sourceStart; @@ -404,8 +404,8 @@ public class AjASTConverter extends ASTConverter { methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED); break; default : - for (int i = 0, max = typeParameters.length; i < max; i++) { - methodDecl.typeParameters().add(convert(typeParameters[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) { + methodDecl.typeParameters().add(convert(typeParameter)); } } } @@ -666,16 +666,16 @@ public class AjASTConverter extends ASTConverter { } TypePattern[] weaverTypePatterns = dp.getParents().getTypePatterns(); List typePatterns = ((DeclareParentsDeclaration) declareDeclaration).parentTypePatterns(); - for (int i = 0; i < weaverTypePatterns.length; i++) { - typePatterns.add(convert(weaverTypePatterns[i])); + for (TypePattern weaverTypePattern : weaverTypePatterns) { + typePatterns.add(convert(weaverTypePattern)); } } else if (declare instanceof DeclarePrecedence) { declareDeclaration = new org.aspectj.org.eclipse.jdt.core.dom.DeclarePrecedenceDeclaration(this.ast); DeclarePrecedence dp = (DeclarePrecedence) declare; TypePattern[] weaverTypePatterns = dp.getPatterns().getTypePatterns(); List typePatterns = ((DeclarePrecedenceDeclaration) declareDeclaration).typePatterns(); - for (int i = 0; i < weaverTypePatterns.length; i++) { - typePatterns.add(convert(weaverTypePatterns[i])); + for (TypePattern weaverTypePattern : weaverTypePatterns) { + typePatterns.add(convert(weaverTypePattern)); } } else if (declare instanceof DeclareSoft) { declareDeclaration = new DeclareSoftDeclaration(this.ast); @@ -763,8 +763,8 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = pointcutDeclaration.arguments; if (parameters != null) { int parametersLength = parameters.length; - for (int i = 0; i < parametersLength; i++) { - pointcutDecl.parameters().add(convert(parameters[i])); + for (Argument parameter : parameters) { + pointcutDecl.parameters().add(convert(parameter)); } } @@ -1141,10 +1141,10 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] expressions = expression.expressions; if (expressions != null) { int length = expressions.length; - for (int i = 0; i < length; i++) { - Expression expr = super.convert(expressions[i]); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression value : expressions) { + Expression expr = super.convert(value); if (this.resolveBindings) { - recordNodes(expr, expressions[i]); + recordNodes(expr, value); } arrayInitializer.expressions().add(expr); } @@ -1505,16 +1505,15 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference[] imports = unit.imports; if (imports != null) { int importLength = imports.length; - for (int i = 0; i < importLength; i++) { - compilationUnit.imports().add(convertImport(imports[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference anImport : imports) { + compilationUnit.imports().add(convertImport(anImport)); } } org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = unit.types; if (types != null) { int typesLength = types.length; - for (int i = 0; i < typesLength; i++) { - org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration declaration = types[i]; + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration declaration : types) { if (CharOperation.equals(declaration.name, TypeConstants.PACKAGE_INFO_NAME)) { continue; } @@ -1908,8 +1907,8 @@ public class AjASTConverter extends ASTConverter { forStatement.initializers().add(variableDeclarationExpression); } else { int initializationsLength = initializations.length; - for (int i = 0; i < initializationsLength; i++) { - Expression initializer = convertToExpression(initializations[i]); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement initialization : initializations) { + Expression initializer = convertToExpression(initialization); if (initializer != null) { forStatement.initializers().add(initializer); } else { @@ -1924,8 +1923,8 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] increments = statement.increments; if (increments != null) { int incrementsLength = increments.length; - for (int i = 0; i < incrementsLength; i++) { - forStatement.updaters().add(convertToExpression(increments[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement increment : increments) { + forStatement.updaters().add(convertToExpression(increment)); } } forStatement.setBody(convert(statement.action)); @@ -2062,8 +2061,8 @@ public class AjASTConverter extends ASTConverter { setTypeNameForAnnotation(annotation, normalAnnotation); org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair[] memberValuePairs = annotation.memberValuePairs; if (memberValuePairs != null) { - for (int i = 0, max = memberValuePairs.length; i < max; i++) { - normalAnnotation.values().add(convert(memberValuePairs[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair memberValuePair : memberValuePairs) { + normalAnnotation.values().add(convert(memberValuePair)); } } int start = annotation.sourceStart; @@ -2149,10 +2148,10 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = allocation.arguments; if (arguments != null) { int length = arguments.length; - for (int i = 0; i < length; i++) { - Expression argument = super.convert(arguments[i]); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression : arguments) { + Expression argument = super.convert(expression); if (this.resolveBindings) { - recordNodes(argument, arguments[i]); + recordNodes(argument, expression); } classInstanceCreation.arguments().add(argument); } @@ -2404,8 +2403,8 @@ public class AjASTConverter extends ASTConverter { org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = statement.statements; if (statements != null) { int statementsLength = statements.length; - for (int i = 0; i < statementsLength; i++) { - switchStatement.statements().add(convert(statements[i])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement value : statements) { + switchStatement.statements().add(convert(value)); } } return switchStatement; @@ -2541,13 +2540,13 @@ public class AjASTConverter extends ASTConverter { if (superInterfaces != null) { switch(this.ast.apiLevel) { case AST.JLS2_INTERNAL : - for (int index = 0, length = superInterfaces.length; index < length; index++) { - typeDecl.internalSuperInterfaces().add(convert(superInterfaces[index])); + for (TypeReference anInterface : superInterfaces) { + typeDecl.internalSuperInterfaces().add(convert(anInterface)); } break; default : - for (int index = 0, length = superInterfaces.length; index < length; index++) { - typeDecl.superInterfaceTypes().add(convertType(superInterfaces[index])); + for (TypeReference superInterface : superInterfaces) { + typeDecl.superInterfaceTypes().add(convertType(superInterface)); } } } @@ -2558,8 +2557,8 @@ public class AjASTConverter extends ASTConverter { typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED); break; default : - for (int index = 0, length = typeParameters.length; index < length; index++) { - typeDecl.typeParameters().add(convert(typeParameters[index])); + for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) { + typeDecl.typeParameters().add(convert(typeParameter)); } } } @@ -2590,8 +2589,8 @@ public class AjASTConverter extends ASTConverter { TypeReference[] bounds = typeParameter.bounds; if (bounds != null) { Type type = null; - for (int index = 0, length = bounds.length; index < length; index++) { - type = convertType(bounds[index]); + for (TypeReference bound : bounds) { + type = convertType(bound); typeParameter2.typeBounds().add(type); end = type.getStartPosition() + type.getLength() - 1; } @@ -2906,8 +2905,8 @@ public class AjASTConverter extends ASTConverter { TypeReference[] typeArguments = parameterizedSingleTypeReference.typeArguments; if (typeArguments != null) { Type type2 = null; - for (int i = 0, max = typeArguments.length; i < max; i++) { - type2 = convertType(typeArguments[i]); + for (TypeReference typeArgument : typeArguments) { + type2 = convertType(typeArgument); ((ParameterizedType) type).typeArguments().add(type2); end = type2.getStartPosition() + type2.getLength() - 1; } @@ -2982,8 +2981,8 @@ public class AjASTConverter extends ASTConverter { int numberOfEnclosingType = 0; int startingIndex = 0; int endingIndex = 0; - for (int i = 0, max = typeArguments.length; i < max; i++) { - if (typeArguments[i] != null) { + for (TypeReference[] typeArgument : typeArguments) { + if (typeArgument != null) { numberOfEnclosingType++; } else if (numberOfEnclosingType == 0) { endingIndex++; @@ -3308,14 +3307,14 @@ public class AjASTConverter extends ASTConverter { private void lookupForScopes() { if (this.pendingNameScopeResolution != null) { - for (Iterator iterator = this.pendingNameScopeResolution.iterator(); iterator.hasNext();) { - Name name = (Name) iterator.next(); + for (Object o : this.pendingNameScopeResolution) { + Name name = (Name) o; this.ast.getBindingResolver().recordScope(name, lookupScope(name)); } } if (this.pendingThisExpressionScopeResolution != null) { - for (Iterator iterator = this.pendingThisExpressionScopeResolution.iterator(); iterator.hasNext();) { - ThisExpression thisExpression = (ThisExpression) iterator.next(); + for (Object o : this.pendingThisExpressionScopeResolution) { + ThisExpression thisExpression = (ThisExpression) o; this.ast.getBindingResolver().recordScope(thisExpression, lookupScope(thisExpression)); } } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjNaiveASTFlattener.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjNaiveASTFlattener.java index 8e950cd42..8244a3a8d 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjNaiveASTFlattener.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjNaiveASTFlattener.java @@ -82,8 +82,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { * (element type: <code>IExtendedModifiers</code>) */ void printModifiers(List ext) { - for (Iterator it = ext.iterator(); it.hasNext(); ) { - ASTNode p = (ASTNode) it.next(); + for (Object o : ext) { + ASTNode p = (ASTNode) o; p.accept(this); this.buffer.append(" ");//$NON-NLS-1$ } @@ -144,8 +144,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { this.buffer.append("@interface ");//$NON-NLS-1$ node.getName().accept(this); this.buffer.append(" {");//$NON-NLS-1$ - for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) { - BodyDeclaration d = (BodyDeclaration) it.next(); + for (Object o : node.bodyDeclarations()) { + BodyDeclaration d = (BodyDeclaration) o; d.accept(this); } this.buffer.append("}\n");//$NON-NLS-1$ @@ -180,8 +180,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { public boolean visit(AnonymousClassDeclaration node) { this.buffer.append("{\n");//$NON-NLS-1$ this.indent++; - for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) { - BodyDeclaration b = (BodyDeclaration) it.next(); + for (Object o : node.bodyDeclarations()) { + BodyDeclaration b = (BodyDeclaration) o; b.accept(this); } this.indent--; @@ -210,9 +210,9 @@ public class AjNaiveASTFlattener extends AjASTVisitor { int dims = at.getDimensions(); Type elementType = at.getElementType(); elementType.accept(this); - for (Iterator it = node.dimensions().iterator(); it.hasNext(); ) { + for (Object o : node.dimensions()) { this.buffer.append("[");//$NON-NLS-1$ - Expression e = (Expression) it.next(); + Expression e = (Expression) o; e.accept(this); this.buffer.append("]");//$NON-NLS-1$ dims--; @@ -283,8 +283,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { public boolean visit(Block node) { this.buffer.append("{\n");//$NON-NLS-1$ this.indent++; - for (Iterator it = node.statements().iterator(); it.hasNext(); ) { - Statement s = (Statement) it.next(); + for (Object o : node.statements()) { + Statement s = (Statement) o; s.accept(this); } this.indent--; @@ -407,12 +407,12 @@ public class AjNaiveASTFlattener extends AjASTVisitor { if (node.getPackage() != null) { node.getPackage().accept(this); } - for (Iterator it = node.imports().iterator(); it.hasNext(); ) { - ImportDeclaration d = (ImportDeclaration) it.next(); + for (Object value : node.imports()) { + ImportDeclaration d = (ImportDeclaration) value; d.accept(this); } - for (Iterator it = node.types().iterator(); it.hasNext(); ) { - AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next(); + for (Object o : node.types()) { + AbstractTypeDeclaration d = (AbstractTypeDeclaration) o; d.accept(this); } return false; @@ -593,8 +593,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { } if (!node.bodyDeclarations().isEmpty()) { this.buffer.append("; ");//$NON-NLS-1$ - for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) { - BodyDeclaration d = (BodyDeclaration) it.next(); + for (Object o : node.bodyDeclarations()) { + BodyDeclaration d = (BodyDeclaration) o; d.accept(this); // other body declarations include trailing punctuation } @@ -723,9 +723,9 @@ public class AjNaiveASTFlattener extends AjASTVisitor { final List extendedOperands = node.extendedOperands(); if (extendedOperands.size() != 0) { this.buffer.append(' '); - for (Iterator it = extendedOperands.iterator(); it.hasNext(); ) { + for (Object extendedOperand : extendedOperands) { this.buffer.append(node.getOperator().toString()).append(' '); - Expression e = (Expression) it.next(); + Expression e = (Expression) extendedOperand; e.accept(this); } } @@ -765,8 +765,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { public boolean visit(Javadoc node) { printIndent(); this.buffer.append("/** ");//$NON-NLS-1$ - for (Iterator it = node.tags().iterator(); it.hasNext(); ) { - ASTNode e = (ASTNode) it.next(); + for (Object o : node.tags()) { + ASTNode e = (ASTNode) o; e.accept(this); } this.buffer.append("\n */\n");//$NON-NLS-1$ @@ -1023,8 +1023,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } - for (Iterator it = node.annotations().iterator(); it.hasNext(); ) { - Annotation p = (Annotation) it.next(); + for (Object o : node.annotations()) { + Annotation p = (Annotation) o; p.accept(this); this.buffer.append(" ");//$NON-NLS-1$ } @@ -1296,8 +1296,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { this.buffer.append(") ");//$NON-NLS-1$ this.buffer.append("{\n");//$NON-NLS-1$ this.indent++; - for (Iterator it = node.statements().iterator(); it.hasNext(); ) { - Statement s = (Statement) it.next(); + for (Object o : node.statements()) { + Statement s = (Statement) o; s.accept(this); this.indent--; // incremented in visit(SwitchCase) } @@ -1336,8 +1336,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { previousRequiresWhiteSpace = true; } boolean previousRequiresNewLine = false; - for (Iterator it = node.fragments().iterator(); it.hasNext(); ) { - ASTNode e = (ASTNode) it.next(); + for (Object o : node.fragments()) { + ASTNode e = (ASTNode) o; // assume text elements include necessary leading and trailing whitespace // but Name, MemberRef, MethodRef, and nested TagElement do not include white space boolean currentIncludesWhiteSpace = (e instanceof TextElement); @@ -1398,8 +1398,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { this.buffer.append("try ");//$NON-NLS-1$ node.getBody().accept(this); this.buffer.append(" ");//$NON-NLS-1$ - for (Iterator it = node.catchClauses().iterator(); it.hasNext(); ) { - CatchClause cc = (CatchClause) it.next(); + for (Object o : node.catchClauses()) { + CatchClause cc = (CatchClause) o; cc.accept(this); } if (node.getFinally() != null) { @@ -1494,8 +1494,8 @@ public class AjNaiveASTFlattener extends AjASTVisitor { this.buffer.append("{\n");//$NON-NLS-1$ this.indent++; BodyDeclaration prev = null; - for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) { - BodyDeclaration d = (BodyDeclaration) it.next(); + for (Object o : node.bodyDeclarations()) { + BodyDeclaration d = (BodyDeclaration) o; if (prev instanceof EnumConstantDeclaration) { // enum constant declarations do not include punctuation if (d instanceof EnumConstantDeclaration) { diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjTypeDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjTypeDeclaration.java index dd3f296a6..5333ec18f 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjTypeDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AjTypeDeclaration.java @@ -173,15 +173,14 @@ public class AjTypeDeclaration extends TypeDeclaration { List bd = bodyDeclarations(); // ajh02: 0 bodyDeclarations :-/ int pointcutCount = 0; - for (Iterator it = bd.listIterator(); it.hasNext(); ) { - if (it.next() instanceof PointcutDeclaration) { + for (Object o : bd) { + if (o instanceof PointcutDeclaration) { pointcutCount++; } } PointcutDeclaration[] pointcuts = new PointcutDeclaration[pointcutCount]; int next = 0; - for (Iterator it = bd.listIterator(); it.hasNext(); ) { - Object decl = it.next(); + for (Object decl : bd) { if (decl instanceof PointcutDeclaration) { pointcuts[next++] = (PointcutDeclaration) decl; } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AspectDeclaration.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AspectDeclaration.java index ff1a2d1ac..de6afab25 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AspectDeclaration.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/org/eclipse/jdt/core/dom/AspectDeclaration.java @@ -211,8 +211,7 @@ public class AspectDeclaration extends AjTypeDeclaration { // ajh02: method added List bd = bodyDeclarations(); List advice = new ArrayList(); - for (Iterator it = bd.listIterator(); it.hasNext();) { - Object decl = it.next(); + for (Object decl : bd) { if (decl instanceof AdviceDeclaration) { advice.add(decl); } diff --git a/org.aspectj.ajdt.core/src/main/java/org/aspectj/tools/ajc/Main.java b/org.aspectj.ajdt.core/src/main/java/org/aspectj/tools/ajc/Main.java index 4e8235cf2..6f7a1dd7c 100644 --- a/org.aspectj.ajdt.core/src/main/java/org/aspectj/tools/ajc/Main.java +++ b/org.aspectj.ajdt.core/src/main/java/org/aspectj/tools/ajc/Main.java @@ -119,8 +119,8 @@ public class Main { } IMessage[] messages = holder.getMessages(kind, orGreater); if (!LangUtil.isEmpty(messages)) { - for (int i = 0; i < messages.length; i++) { - sink.add(MessagePrinter.render(messages[i])); + for (IMessage message : messages) { + sink.add(MessagePrinter.render(message)); } } } @@ -264,8 +264,8 @@ public class Main { boolean skipExit = false; if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit - for (int i = 0; i < args.length; i++) { - if ("-noExit".equals(args[i])) { + for (String arg : args) { + if ("-noExit".equals(arg)) { skipExit = true; break; } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java index 5bb86a18c..1f936661e 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java @@ -97,11 +97,11 @@ public class BuildArgParserTestCase extends TestCase { List cp = config.getClasspath(); boolean jar1Found = false; boolean jar2Found = false; - for (Iterator iter = cp.iterator(); iter.hasNext();) { - String element = (String) iter.next(); - if (element.indexOf("1.jar") != -1) jar1Found = true; - if (element.indexOf("2.jar") != -1) jar2Found = true; - } + for (Object o : cp) { + String element = (String) o; + if (element.indexOf("1.jar") != -1) jar1Found = true; + if (element.indexOf("2.jar") != -1) jar2Found = true; + } assertTrue( config.getClasspath().toString(), jar1Found); @@ -373,11 +373,11 @@ public class BuildArgParserTestCase extends TestCase { List cp = config.getClasspath(); boolean jar1Found = false; boolean jar2Found = false; - for (Iterator iter = cp.iterator(); iter.hasNext();) { - String element = (String) iter.next(); - if (element.indexOf("1.jar") != -1) jar1Found = true; - if (element.indexOf("2.jar") != -1) jar2Found = true; - } + for (Object o : cp) { + String element = (String) o; + if (element.indexOf("1.jar") != -1) jar1Found = true; + if (element.indexOf("2.jar") != -1) jar2Found = true; + } assertTrue( config.getClasspath().toString(), jar1Found); @@ -405,8 +405,8 @@ public class BuildArgParserTestCase extends TestCase { String b = new File(TEST_DIR + "../bug-40257/d1/d2/B.java").getCanonicalPath(); String c = new File(TEST_DIR + "../bug-40257/d3/C.java").getCanonicalPath(); List pathList = new ArrayList(); - for (Iterator it = config.getFiles().iterator(); it.hasNext(); ) { - pathList.add(((File)it.next()).getCanonicalPath()); + for (File file : config.getFiles()) { + pathList.add(file.getCanonicalPath()); } assertTrue(pathList.contains(a)); assertTrue(pathList.contains(b)); @@ -544,9 +544,9 @@ public class BuildArgParserTestCase extends TestCase { private void checkPathSubset(List path) throws IOException { String files[] = { "aspectjJar.file", "jarChild", "parent.zip" }; - for (int i = 0; i < files.length; i++) { - File file = new File(NONSTANDARD_JAR_DIR+files[i]); - assertTrue("bad path: " + path, path.contains(file.getCanonicalPath())); + for (String s : files) { + File file = new File(NONSTANDARD_JAR_DIR + s); + assertTrue("bad path: " + path, path.contains(file.getCanonicalPath())); } } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/CommandTestCase.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/CommandTestCase.java index bcc4ad172..53053d8b3 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/CommandTestCase.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/CommandTestCase.java @@ -74,8 +74,8 @@ public abstract class CommandTestCase extends TestCase { args.add("-g"); // XXX need this to get sourcefile and line numbers, shouldn't - for (int i = 0; i < extraArgs.length; i++) { - args.add(extraArgs[i]); + for (String extraArg : extraArgs) { + args.add(extraArg); } args.add(Constants.TESTDATA_PATH + "/" + source); @@ -132,10 +132,9 @@ public abstract class CommandTestCase extends TestCase { assertTrue("expected error", nErrors > 0); } else { List errors = new ArrayList(Arrays.asList(myHandler.getErrors())); - for (int i = 0, len = expectedErrors.length; i < len; i++) { - int line = expectedErrors[i]; + for (int line : expectedErrors) { boolean found = false; - for (Iterator iter = errors.iterator(); iter.hasNext();) { + for (Iterator iter = errors.iterator(); iter.hasNext(); ) { IMessage m = (IMessage) iter.next(); if (m.getSourceLocation() != null && m.getSourceLocation().getLine() == line) { found = true; diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/DeclareParentsTest.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/DeclareParentsTest.java index 7ca59d741..33f8a48e9 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/DeclareParentsTest.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/DeclareParentsTest.java @@ -281,10 +281,9 @@ public class DeclareParentsTest extends AjcTestCase { // /////////////////////////////////////////////////////////////////////////// // Check the error messages are comparable (allow for differing orderings) if (compareErrors) { - for (Iterator<IMessage> iter = binaryErrorMessages.iterator(); iter.hasNext();) { - IMessage binaryMessage = iter.next(); + for (IMessage binaryMessage : binaryErrorMessages) { IMessage correctSourceMessage = null; - for (Iterator<IMessage> iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage == null;) { + for (Iterator<IMessage> iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage == null; ) { IMessage sourceMessage = iterator.next(); if (sourceMessage.getMessage().equals(binaryMessage.getMessage())) { @@ -298,8 +297,7 @@ public class DeclareParentsTest extends AjcTestCase { sourceErrorMessages.remove(correctSourceMessage); } if (sourceErrorMessages.size() > 0) { - for (Iterator<IMessage> iter = sourceErrorMessages.iterator(); iter.hasNext();) { - IMessage srcMsg = iter.next(); + for (IMessage srcMsg : sourceErrorMessages) { System.err.println("This error message from source compilation '" + srcMsg + "' didn't occur during binary weaving."); } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/IncrementalCase.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/IncrementalCase.java index 36fe2e92c..6b96c9469 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/IncrementalCase.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/IncrementalCase.java @@ -49,9 +49,9 @@ public class IncrementalCase { // XXX NOT bound to junit - bridge tests? MessageHandler h = new MessageHandler(); // boolean result; StringBuffer sb = new StringBuffer(); - for (int i = 0; i < args.length; i++) { - sb.append("\n###### results for " + args[i]); - sb.append("\n" + me.run(new File(args[i]), h) + ": " + h); + for (String arg : args) { + sb.append("\n###### results for " + arg); + sb.append("\n" + me.run(new File(arg), h) + ": " + h); } System.err.flush(); System.out.flush(); @@ -260,9 +260,9 @@ public class IncrementalCase { // XXX NOT bound to junit - bridge tests? List<String> normalizeFilenames(String[] ra) { // XXX util ArrayList<String> result = new ArrayList<>(); if (null != ra) { - for (int i = 0; i < ra.length; i++) { - result.add(normalizeFilename(ra[i])); - } + for (String s : ra) { + result.add(normalizeFilename(s)); + } if (1 < ra.length) { Collections.sort(result); } @@ -332,29 +332,28 @@ public class IncrementalCase { // XXX NOT bound to junit - bridge tests? info(handler, context); BitSet foundSet = new BitSet(10); - for (int i = 0; i < exp.length; i++) { - final int expLine = exp[i]; + for (final int expLine : exp) { boolean found = false; for (int j = 0; !found && (j < messages.length); j++) { ISourceLocation sl = messages[j].getSourceLocation(); found = ((null != sl) && (expLine == sl.getLine())); if (found) { - info(handler, "found " + label + " for: " + exp[i]); + info(handler, "found " + label + " for: " + expLine); if (foundSet.get(j)) { info( - handler, - "duplicate " + label + " expected: " + exp[i]); + handler, + "duplicate " + label + " expected: " + expLine); } foundSet.set(j); } } if (!found) { String s = - "expected " - + label - + " not found: " - + exp[i] - + context; + "expected " + + label + + " not found: " + + expLine + + context; fail(handler, s); // bad short-circuit if (!result) { result = false; diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/WorkingTestMain.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/WorkingTestMain.java index 307232643..b1ebd10ca 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/WorkingTestMain.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/ajdt/internal/compiler/batch/WorkingTestMain.java @@ -79,14 +79,14 @@ public class WorkingTestMain { args.add("-classpath"); args.add(Constants.aspectjrtClasspath()); - - for (int i=0; i < argfiles.length; i++) { - args.add("@" + examplesDir + argfiles[i]); + + for (String argfile : argfiles) { + args.add("@" + examplesDir + argfile); } CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS); - for (int i=0; i < classes.length; i++) { - TestUtil.runMain("out", classes[i]); + for (String aClass : classes) { + TestUtil.runMain("out", aClass); } } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjAST5Test.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjAST5Test.java index 213cf0e2c..c41e07fe1 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjAST5Test.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjAST5Test.java @@ -33,42 +33,40 @@ public class AjAST5Test extends AjASTTestCase { AjAST ajast = createAjAST(); AspectDeclaration d = ajast.newAspectDeclaration(); List props = AspectDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("perClause")) { assertNull("AspectDeclaration's " + element.getId() + " property" + - "should be null since we haven't set it yet", - d.getStructuralProperty(element)); + "should be null since we haven't set it yet", + d.getStructuralProperty(element)); } } else if (o instanceof SimplePropertyDescriptor) { - SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; + SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; assertNotNull("AspectDeclaration's " + element.getId() + " property" + - "should not be null since it is a boolean", + "should not be null since it is a boolean", d.getStructuralProperty(element)); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("perClause")) { PerTypeWithin ptw = ajast.newPerTypeWithin(); - d.setStructuralProperty(element,ptw); + d.setStructuralProperty(element, ptw); assertEquals("AspectDeclaration's perClause property should" + - " now be a perTypeWithin",ptw,d.getStructuralProperty(element)); + " now be a perTypeWithin", ptw, d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc - } + } } else if (o instanceof SimplePropertyDescriptor) { - SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; - if (element.getId().equals("privileged")) { + SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; + if (element.getId().equals("privileged")) { Boolean b = new Boolean(true); - d.setStructuralProperty(element,b); + d.setStructuralProperty(element, b); assertEquals("AspectDeclaration's isPrivileged property should" + - " now be a boolean",b,d.getStructuralProperty(element)); - } + " now be a boolean", b, d.getStructuralProperty(element)); + } } } } @@ -77,26 +75,24 @@ public class AjAST5Test extends AjASTTestCase { AjAST ajast = createAjAST(); AjTypeDeclaration d = ajast.newAjTypeDeclaration(); List props = AjTypeDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; if (element.getId().equals("aspect")) { assertNotNull("AjTypeDeclaration's " + element.getId() + " property" + - " should not be null since it is a boolean", - d.getStructuralProperty(element)); - } + " should not be null since it is a boolean", + d.getStructuralProperty(element)); + } } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; if (element.getId().equals("aspect")) { Boolean b = new Boolean(true); - d.setStructuralProperty(element,b); + d.setStructuralProperty(element, b); assertEquals("AjTypeDeclaration's aspect property should" + - " now be a SignaturePattern",b,d.getStructuralProperty(element)); + " now be a SignaturePattern", b, d.getStructuralProperty(element)); } } } @@ -106,51 +102,49 @@ public class AjAST5Test extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration(); List props = DeclareParentsDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor)o; + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; assertNull("DeclareParentsDeclaration's " + element.getId() + " property" + - "should be null since we haven't set it yet", - d.getStructuralProperty(element)); + "should be null since we haven't set it yet", + d.getStructuralProperty(element)); } else if (o instanceof ChildListPropertyDescriptor) { - ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o; + ChildListPropertyDescriptor element = (ChildListPropertyDescriptor) o; assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" + - "should not be null since it is a list", + "should not be null since it is a list", d.getStructuralProperty(element)); assertEquals("should only be able to put TypePattern's into the list", - TypePattern.class,element.getElementType()); + TypePattern.class, element.getElementType()); } else if (o instanceof SimplePropertyDescriptor) { - SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; + SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" + - "should not be null since it is a boolean", - d.getStructuralProperty(element)); + "should not be null since it is a boolean", + d.getStructuralProperty(element)); } else { fail("unknown PropertyDescriptor associated with DeclareParentsDeclaration: " + o); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("childTypePattern")) { DefaultTypePattern dtp = ajast.newDefaultTypePattern(); - d.setStructuralProperty(element,dtp); + d.setStructuralProperty(element, dtp); assertEquals("DeclareParentsDeclaration's typePattern property should" + - " now be a DefaultTypePattern",dtp,d.getStructuralProperty(element)); + " now be a DefaultTypePattern", dtp, d.getStructuralProperty(element)); } else if (element.getId().equals("javadoc")) { // do nothing since makes no sense to have javadoc } else { fail("unknown property for DeclareParentsDeclaration"); - } + } } else if (o instanceof SimplePropertyDescriptor) { - SimplePropertyDescriptor element = (SimplePropertyDescriptor)o; - if (element.getId().equals("isExtends")) { + SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; + if (element.getId().equals("isExtends")) { Boolean b = new Boolean(true); - d.setStructuralProperty(element,b); + d.setStructuralProperty(element, b); assertEquals("DeclareParentsDeclaration's isExtends property should" + - " now be a boolean",b,d.getStructuralProperty(element)); - } + " now be a boolean", b, d.getStructuralProperty(element)); + } } } } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTest.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTest.java index 96e71cb7e..e4c49b48c 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTest.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTest.java @@ -393,8 +393,7 @@ public class AjASTTest extends AjASTTestCase { boolean foundName = false; boolean foundParamList = false; boolean foundDesignator = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if ((o instanceof ChildPropertyDescriptor)) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; String id = element.getId(); @@ -439,8 +438,7 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); PointcutDeclaration d = ajast.newPointcutDeclaration(); List props = PointcutDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("name")) { @@ -467,8 +465,7 @@ public class AjASTTest extends AjASTTestCase { fail("unknown PropertyDescriptor associated with PointcutDeclaration: " + o); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("designator")) { @@ -505,8 +502,7 @@ public class AjASTTest extends AjASTTestCase { boolean foundPerClause = false; boolean foundIsPrivileged = false; boolean foundIsAspect = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if ((o instanceof ChildPropertyDescriptor)) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; String id = element.getId(); @@ -735,8 +731,7 @@ public class AjASTTest extends AjASTTestCase { ajast.newAjTypeDeclaration(); List props = AjTypeDeclaration.propertyDescriptors(AST.JLS3); boolean foundAspect = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; String id = element.getId(); @@ -770,8 +765,7 @@ public class AjASTTest extends AjASTTestCase { boolean foundPrivileged = false; boolean foundPerClause = false; // boolean foundAspect = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; String id = element.getId(); @@ -802,8 +796,7 @@ public class AjASTTest extends AjASTTestCase { ajast.newTypeDeclaration(); List props = TypeDeclaration.propertyDescriptors(AST.JLS3); boolean foundAspect = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof SimplePropertyDescriptor) { SimplePropertyDescriptor element = (SimplePropertyDescriptor) o; String id = element.getId(); @@ -831,8 +824,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -883,8 +876,8 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration(); List props = DeclareAtFieldDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtFieldDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); @@ -893,8 +886,8 @@ public class AjASTTest extends AjASTTestCase { + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element, p); @@ -929,8 +922,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -981,8 +974,8 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration(); List props = DeclareAtMethodDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtMethodDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); @@ -991,8 +984,8 @@ public class AjASTTest extends AjASTTestCase { + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element, p); @@ -1027,8 +1020,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -1079,8 +1072,8 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration(); List props = DeclareAtConstructorDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtConstructorDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); @@ -1089,8 +1082,8 @@ public class AjASTTest extends AjASTTestCase { + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pattern")) { SignaturePattern p = ajast.newSignaturePattern(); d.setStructuralProperty(element, p); @@ -1125,8 +1118,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPattern = false; boolean foundAnnotationName = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -1177,8 +1170,8 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration(); List props = DeclareAtTypeDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; if (element.getId().equals("annotationName")) { assertNotNull("DeclareAtTypeDeclaration's " + element.getId() + " property" + " should not be null since it is lazily created", d.getStructuralProperty(element)); @@ -1187,8 +1180,8 @@ public class AjASTTest extends AjASTTestCase { + " should be null since we haven't set it yet", d.getStructuralProperty(element)); } } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pattern")) { DefaultTypePattern p = ajast.newDefaultTypePattern(); d.setStructuralProperty(element, p); @@ -1223,8 +1216,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundMessage = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -1273,13 +1266,13 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration(); List props = DeclareErrorDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; assertNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element, p); @@ -1315,8 +1308,7 @@ public class AjASTTest extends AjASTTestCase { boolean foundTypePattern = false; boolean foundIsExtends = false; boolean foundTypePatternList = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if ((o instanceof ChildPropertyDescriptor)) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; String id = element.getId(); @@ -1400,8 +1392,7 @@ public class AjASTTest extends AjASTTestCase { List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3); boolean foundJavadoc = false; boolean foundTypePatterns = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if ((o instanceof ChildPropertyDescriptor) && ((ChildPropertyDescriptor) o).getId().equals("javadoc")) { foundJavadoc = true; } else if ((o instanceof ChildListPropertyDescriptor) @@ -1440,8 +1431,7 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration(); List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : props) { if (o instanceof ChildPropertyDescriptor) { ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; assertNull("DeclareErrorDeclaration's " + element.getId() + " property" @@ -1473,8 +1463,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundTypePattern = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -1523,13 +1513,13 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration(); List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; assertNull("DeclareSoftDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element, p); @@ -1564,8 +1554,8 @@ public class AjASTTest extends AjASTTestCase { boolean foundJavadoc = false; boolean foundPointcut = false; boolean foundMessage = false; - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; String id = element.getId(); if (id.equals("javadoc")) { foundJavadoc = true; @@ -1614,13 +1604,13 @@ public class AjASTTest extends AjASTTestCase { AjAST ajast = createAjAST(); DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration(); List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3); - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object o : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) o; assertNull("DeclareWarningDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet", d.getStructuralProperty(element)); } - for (Iterator iter = props.iterator(); iter.hasNext();) { - ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next(); + for (Object prop : props) { + ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop; if (element.getId().equals("pointcut")) { AndPointcut p = ajast.newAndPointcut(); d.setStructuralProperty(element, p); diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTestCase.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTestCase.java index 94d57c862..b3870c6e8 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTestCase.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjASTTestCase.java @@ -88,9 +88,9 @@ public abstract class AjASTTestCase extends TestCase { protected List<SourceRange> getSourceRanges(int[][] sourceRanges) { List<SourceRange> convertedRanges = new ArrayList<SourceRange>(); - for (int i = 0; i < sourceRanges.length; i++) { - convertedRanges.add(new SourceRange(sourceRanges[i][0], - sourceRanges[i][1])); + for (int[] sourceRange : sourceRanges) { + convertedRanges.add(new SourceRange(sourceRange[0], + sourceRange[1])); } return convertedRanges; } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/Ajc.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/Ajc.java index facab0e7e..671b310cc 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/Ajc.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/Ajc.java @@ -258,8 +258,8 @@ public class Ajc { private boolean hasSpecifiedIncremental(String[] args) { if (args == null) return false; - for (int i = 0; i < args.length; i++) { - if (args[i].equals("-incremental")) + for (String arg : args) { + if (arg.equals("-incremental")) return true; } return false; @@ -313,14 +313,14 @@ public class Ajc { } private void addMessagesTo(List<IMessage> aList, IMessage[] messages) { - for (int i = 0; i < messages.length; i++) { - aList.add(messages[i]); + for (IMessage message : messages) { + aList.add(message); } } private boolean isIncremental(String[] args) { - for (int i = 0; i < args.length; i++) { - if (args[i].trim().equals("-incremental")) + for (String arg : args) { + if (arg.trim().equals("-incremental")) return true; } return false; @@ -428,10 +428,10 @@ public class Ajc { return (toMatch.equals(prefix)); } }); - for (int i = 0; i < toCopy.length; i++) { - String toPath = relativeToPath + toCopy[i]; + for (String s : toCopy) { + String toPath = relativeToPath + s; to = new File(sandbox, toPath); - FileUtil.copyFile(new File(from.getParentFile(), toCopy[i]), to); + FileUtil.copyFile(new File(from.getParentFile(), s), to); } } else { FileUtil.copyFile(from, ret); @@ -450,8 +450,7 @@ public class Ajc { System.out.println("start of AJDE structure model:" + prefix); //$NON-NLS-1$ IRelationshipMap asmRelMap = model.getRelationshipMap(); - for (Iterator<String> iter = asmRelMap.getEntries().iterator(); iter.hasNext();) { - String sourceOfRelationship = iter.next(); + for (String sourceOfRelationship : asmRelMap.getEntries()) { System.err.println("Examining source relationship handle: " + sourceOfRelationship); List<IRelationship> relationships = null; if (useHandles) { @@ -461,11 +460,10 @@ public class Ajc { relationships = asmRelMap.get(ipe); } if (relationships != null) { - for (Iterator<IRelationship> iterator = relationships.iterator(); iterator.hasNext();) { - Relationship rel = (Relationship) iterator.next(); + for (IRelationship relationship : relationships) { + Relationship rel = (Relationship) relationship; List<String> targets = rel.getTargets(); - for (Iterator<String> iterator2 = targets.iterator(); iterator2.hasNext();) { - String t = (String) iterator2.next(); + for (String t : targets) { IProgramElement link = model.getHierarchy().findElementForHandle(t); System.out.println(""); //$NON-NLS-1$ System.out.println(" sourceOfRelationship " + sourceOfRelationship); //$NON-NLS-1$ diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjcTestCase.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjcTestCase.java index 3d4572057..a9442de73 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjcTestCase.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/AjcTestCase.java @@ -1010,9 +1010,9 @@ public abstract class AjcTestCase extends TestCase { buff.append("Unexpected "); buff.append(type); buff.append(" messages:\n"); - for (Iterator iter = messages.iterator(); iter.hasNext();) { + for (Object message : messages) { buff.append("\t"); - buff.append(iter.next().toString()); + buff.append(message.toString()); buff.append("\n"); } } diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/CompilationResult.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/CompilationResult.java index 1265e4502..a7d661038 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/CompilationResult.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/CompilationResult.java @@ -174,49 +174,49 @@ public class CompilationResult { } buff.append("\n"); int msgNo = 1; - for (Iterator iter = failMessages.iterator(); iter.hasNext();) { + for (IMessage failMessage : failMessages) { buff.append("[fail "); buff.append(msgNo++); buff.append("] "); - buff.append(iter.next().toString()); + buff.append(failMessage.toString()); buff.append("\n"); } msgNo = 1; - for (Iterator iter = errorMessages.iterator(); iter.hasNext();) { + for (IMessage errorMessage : errorMessages) { buff.append("[error "); buff.append(msgNo++); buff.append("] "); - buff.append(iter.next().toString()); + buff.append(errorMessage.toString()); buff.append("\n"); } msgNo = 1; - for (Iterator iter = warningMessages.iterator(); iter.hasNext();) { + for (IMessage warningMessage : warningMessages) { buff.append("[warning "); buff.append(msgNo++); buff.append("] "); - buff.append(iter.next().toString()); + buff.append(warningMessage.toString()); buff.append("\n"); } msgNo = 1; - for (Iterator iter = infoMessages.iterator(); iter.hasNext();) { + for (IMessage infoMessage : infoMessages) { buff.append("[info "); buff.append(msgNo++); buff.append("] "); - buff.append(iter.next().toString()); + buff.append(infoMessage.toString()); buff.append("\n"); } msgNo = 1; - for (Iterator iter = weaveMessages.iterator(); iter.hasNext();) { + for (IMessage weaveMessage : weaveMessages) { buff.append("[weaveInfo "); buff.append(msgNo++); buff.append("] "); - buff.append(iter.next().toString()); + buff.append(weaveMessage.toString()); buff.append("\n"); } buff.append("\ncommand was: 'ajc"); - for (int i = 0; i < args.length; i++) { + for (String arg : args) { buff.append(' '); - buff.append(args[i]); + buff.append(arg); } buff.append("'\n"); return buff.toString(); diff --git a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/DelegatingOutputStream.java b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/DelegatingOutputStream.java index 019a51849..9dff188ed 100644 --- a/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/DelegatingOutputStream.java +++ b/org.aspectj.ajdt.core/src/test/java/org/aspectj/tools/ajc/DelegatingOutputStream.java @@ -29,45 +29,45 @@ public class DelegatingOutputStream extends OutputStream { public void close() throws IOException { target.close(); - - for (Iterator i = delegates.iterator(); i.hasNext();) { - OutputStream delegate = (OutputStream)i.next(); + + for (Object o : delegates) { + OutputStream delegate = (OutputStream) o; delegate.close(); } } public void flush() throws IOException { target.flush(); - - for (Iterator i = delegates.iterator(); i.hasNext();) { - OutputStream delegate = (OutputStream)i.next(); + + for (Object o : delegates) { + OutputStream delegate = (OutputStream) o; delegate.flush(); } } public void write(byte[] b, int off, int len) throws IOException { if (verbose) target.write(b, off, len); - - for (Iterator i = delegates.iterator(); i.hasNext();) { - OutputStream delegate = (OutputStream)i.next(); - delegate.write(b,off,len); + + for (Object o : delegates) { + OutputStream delegate = (OutputStream) o; + delegate.write(b, off, len); } } public void write(byte[] b) throws IOException { if (verbose) target.write(b); - - for (Iterator i = delegates.iterator(); i.hasNext();) { - OutputStream delegate = (OutputStream)i.next(); + + for (Object o : delegates) { + OutputStream delegate = (OutputStream) o; delegate.write(b); } } public void write(int b) throws IOException { if (verbose) target.write(b); - - for (Iterator i = delegates.iterator(); i.hasNext();) { - OutputStream delegate = (OutputStream)i.next(); + + for (Object o : delegates) { + OutputStream delegate = (OutputStream) o; delegate.write(b); } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractAnnotationAJ.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractAnnotationAJ.java index 503d6b3b5..e098251d1 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractAnnotationAJ.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractAnnotationAJ.java @@ -121,10 +121,9 @@ public abstract class AbstractAnnotationAJ implements AnnotationAJ { */ private final AnnotationAJ retrieveAnnotationOnAnnotation(UnresolvedType requiredAnnotationSignature) { AnnotationAJ[] annos = type.getAnnotations(); - for (int i = 0; i < annos.length; i++) { - AnnotationAJ a = annos[i]; + for (AnnotationAJ a : annos) { if (a.getTypeSignature().equals(requiredAnnotationSignature.getSignature())) { - return annos[i]; + return a; } } return null; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractReferenceTypeDelegate.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractReferenceTypeDelegate.java index 7f3fb60ee..bdddec51e 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractReferenceTypeDelegate.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AbstractReferenceTypeDelegate.java @@ -120,8 +120,8 @@ public abstract class AbstractReferenceTypeDelegate implements ReferenceTypeDele AbstractReferenceTypeDelegate outerObjectType = (AbstractReferenceTypeDelegate) outerDelegate; if (outerObjectType.isNested()) { GenericSignature.FormalTypeParameter[] parentParams = outerObjectType.getFormalTypeParametersFromOuterClass(); - for (int i = 0; i < parentParams.length; i++) { - typeParameters.add(parentParams[i]); + for (GenericSignature.FormalTypeParameter parentParam : parentParams) { + typeParameters.add(parentParam); } } GenericSignature.ClassSignature outerSig = outerObjectType.getGenericClassTypeSignature(); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AjAttribute.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AjAttribute.java index 781227141..e76c88f88 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AjAttribute.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/AjAttribute.java @@ -374,9 +374,9 @@ public abstract class AjAttribute { } s.writeInt(lineBreaks.length); int previous = 0; - for (int i = 0, max = lineBreaks.length; i < max; i++) { - s.writeShort(lineBreaks[i] - previous); - previous = lineBreaks[i]; + for (int lineBreak : lineBreaks) { + s.writeShort(lineBreak - previous); + previous = lineBreak; } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ArrayReferenceType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ArrayReferenceType.java index aa4fa55c0..81acaadfe 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ArrayReferenceType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ArrayReferenceType.java @@ -119,8 +119,8 @@ public class ArrayReferenceType extends ReferenceType { public TypeVariable[] getTypeVariables() { if (this.typeVariables == null && componentType.getTypeVariables() != null) { this.typeVariables = componentType.getTypeVariables(); - for (int i = 0; i < this.typeVariables.length; i++) { - this.typeVariables[i].resolve(world); + for (TypeVariable typeVariable : this.typeVariables) { + typeVariable.resolve(world); } } return this.typeVariables; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/BoundedReferenceType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/BoundedReferenceType.java index e0a7a680e..ad434575a 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/BoundedReferenceType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/BoundedReferenceType.java @@ -131,14 +131,14 @@ public class BoundedReferenceType extends ReferenceType { if (kind==SUPER){ ret.append("-"); ret.append(lowerBound.getSignatureForAttribute()); - for (int i=0;i<additionalInterfaceBounds.length;i++) { - ret.append(additionalInterfaceBounds[i].getSignatureForAttribute()); + for (ReferenceType additionalInterfaceBound : additionalInterfaceBounds) { + ret.append(additionalInterfaceBound.getSignatureForAttribute()); } } else if (kind==EXTENDS) { ret.append("+"); ret.append(upperBound.getSignatureForAttribute()); - for (int i=0;i<additionalInterfaceBounds.length;i++) { - ret.append(additionalInterfaceBounds[i].getSignatureForAttribute()); + for (ReferenceType additionalInterfaceBound : additionalInterfaceBounds) { + ret.append(additionalInterfaceBound.getSignatureForAttribute()); } } else if (kind==UNBOUND) { ret.append("*"); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembers.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembers.java index 8e41c0a82..b6ddd2e6e 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembers.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembers.java @@ -186,8 +186,7 @@ public class CrosscuttingMembers { } // Check we haven't already got a munger for this: String signatureToLookFor = typeToExpose.getSignature(); - for (Iterator<ConcreteTypeMunger> iterator = typeMungers.iterator(); iterator.hasNext();) { - ConcreteTypeMunger cTM = iterator.next(); + for (ConcreteTypeMunger cTM : typeMungers) { ResolvedTypeMunger rTM = cTM.getMunger(); if (rTM != null && rTM instanceof ExposeTypeMunger) { String exposedType = ((ExposeTypeMunger) rTM).getExposedTypeSignature(); @@ -345,8 +344,7 @@ public class CrosscuttingMembers { Set<Object> theseTypeMungers = new HashSet<Object>(); Set<Object> otherTypeMungers = new HashSet<Object>(); if (!careAboutShadowMungers) { - for (Iterator<ConcreteTypeMunger> iter = typeMungers.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : typeMungers) { if (o instanceof ConcreteTypeMunger) { ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) o; if (!typeMunger.existsToSupportShadowMunging()) { @@ -357,8 +355,7 @@ public class CrosscuttingMembers { } } - for (Iterator<ConcreteTypeMunger> iter = other.typeMungers.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : other.typeMungers) { if (o instanceof ConcreteTypeMunger) { ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) o; if (!typeMunger.existsToSupportShadowMunging()) { @@ -435,15 +432,13 @@ public class CrosscuttingMembers { if (!careAboutShadowMungers) { // this means we are in front end compilation and if the differences are purely mixin parents, we can continue OK Set<DeclareParents> trimmedThis = new HashSet<DeclareParents>(); - for (Iterator<DeclareParents> iterator = declareParents.iterator(); iterator.hasNext();) { - DeclareParents decp = iterator.next(); + for (DeclareParents decp : declareParents) { if (!decp.isMixin()) { trimmedThis.add(decp); } } Set<DeclareParents> trimmedOther = new HashSet<DeclareParents>(); - for (Iterator<DeclareParents> iterator = other.declareParents.iterator(); iterator.hasNext();) { - DeclareParents decp = iterator.next(); + for (DeclareParents decp : other.declareParents) { if (!decp.isMixin()) { trimmedOther.add(decp); } @@ -490,11 +485,11 @@ public class CrosscuttingMembers { if (theseInlinedAroundMungers.size() != otherInlinedAroundMungers.size()) { return false; } - for (Iterator<ShadowMunger> iter = theseInlinedAroundMungers.iterator(); iter.hasNext();) { - Advice thisAdvice = (Advice) iter.next(); + for (ShadowMunger theseInlinedAroundMunger : theseInlinedAroundMungers) { + Advice thisAdvice = (Advice) theseInlinedAroundMunger; boolean foundIt = false; - for (Iterator<ShadowMunger> iterator = otherInlinedAroundMungers.iterator(); iterator.hasNext();) { - Advice otherAdvice = (Advice) iterator.next(); + for (ShadowMunger otherInlinedAroundMunger : otherInlinedAroundMungers) { + Advice otherAdvice = (Advice) otherInlinedAroundMunger; if (thisAdvice.equals(otherAdvice)) { if (thisAdvice.getSignature() instanceof ResolvedMemberImpl) { if (((ResolvedMemberImpl) thisAdvice.getSignature()).isEquivalentTo(otherAdvice.getSignature())) { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembersSet.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembersSet.java index 969f96ece..a3d97ea89 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembersSet.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/CrosscuttingMembersSet.java @@ -140,16 +140,14 @@ public class CrosscuttingMembersSet { // System.err.println("Looking at descendants of "+aspectType.getName()); Set<ResolvedType> knownAspects = members.keySet(); Set<ResolvedType> toBeReplaced = new HashSet<ResolvedType>(); - for (Iterator<ResolvedType> it = knownAspects.iterator(); it.hasNext();) { - ResolvedType candidateDescendant = it.next(); + for (ResolvedType candidateDescendant : knownAspects) { // allowMissing = true - if something is missing, it really probably is not a descendant if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant, true))) { toBeReplaced.add(candidateDescendant); } } boolean change = false; - for (Iterator<ResolvedType> it = toBeReplaced.iterator(); it.hasNext();) { - ResolvedType next = it.next(); + for (ResolvedType next : toBeReplaced) { boolean thisChange = addOrReplaceAspect(next, inWeavePhase); change = change || thisChange; } @@ -195,8 +193,8 @@ public class CrosscuttingMembersSet { public List<ShadowMunger> getShadowMungers() { if (shadowMungers == null) { List<ShadowMunger> ret = new ArrayList<ShadowMunger>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getShadowMungers()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getShadowMungers()); } shadowMungers = ret; } @@ -283,8 +281,8 @@ public class CrosscuttingMembersSet { public List<ConcreteTypeMunger> getLateTypeMungers() { if (lateTypeMungers == null) { List<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getLateTypeMungers()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getLateTypeMungers()); } lateTypeMungers = ret; } @@ -294,8 +292,8 @@ public class CrosscuttingMembersSet { public List<DeclareSoft> getDeclareSofts() { if (declareSofts == null) { Set<DeclareSoft> ret = new HashSet<DeclareSoft>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareSofts()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareSofts()); } declareSofts = new ArrayList<DeclareSoft>(); declareSofts.addAll(ret); @@ -306,8 +304,8 @@ public class CrosscuttingMembersSet { public List<DeclareParents> getDeclareParents() { if (declareParents == null) { Set<DeclareParents> ret = new HashSet<DeclareParents>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareParents()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareParents()); } declareParents = new ArrayList<DeclareParents>(); declareParents.addAll(ret); @@ -321,8 +319,8 @@ public class CrosscuttingMembersSet { public List<DeclareAnnotation> getDeclareAnnotationOnTypes() { if (declareAnnotationOnTypes == null) { Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareAnnotationOnTypes()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareAnnotationOnTypes()); } declareAnnotationOnTypes = new ArrayList<DeclareAnnotation>(); declareAnnotationOnTypes.addAll(ret); @@ -336,8 +334,8 @@ public class CrosscuttingMembersSet { public List<DeclareAnnotation> getDeclareAnnotationOnFields() { if (declareAnnotationOnFields == null) { Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareAnnotationOnFields()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareAnnotationOnFields()); } declareAnnotationOnFields = new ArrayList<DeclareAnnotation>(); declareAnnotationOnFields.addAll(ret); @@ -351,8 +349,8 @@ public class CrosscuttingMembersSet { public List<DeclareAnnotation> getDeclareAnnotationOnMethods() { if (declareAnnotationOnMethods == null) { Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareAnnotationOnMethods()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareAnnotationOnMethods()); } declareAnnotationOnMethods = new ArrayList<DeclareAnnotation>(); declareAnnotationOnMethods.addAll(ret); @@ -367,8 +365,8 @@ public class CrosscuttingMembersSet { public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() { if (declareTypeEows == null) { Set<DeclareTypeErrorOrWarning> ret = new HashSet<DeclareTypeErrorOrWarning>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareTypeErrorOrWarning()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareTypeErrorOrWarning()); } declareTypeEows = new ArrayList<DeclareTypeErrorOrWarning>(); declareTypeEows.addAll(ret); @@ -379,8 +377,8 @@ public class CrosscuttingMembersSet { public List<Declare> getDeclareDominates() { if (declareDominates == null) { List<Declare> ret = new ArrayList<Declare>(); - for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) { - ret.addAll(i.next().getDeclareDominates()); + for (CrosscuttingMembers crosscuttingMembers : members.values()) { + ret.addAll(crosscuttingMembers.getDeclareDominates()); } declareDominates = ret; } @@ -389,10 +387,8 @@ public class CrosscuttingMembersSet { public ResolvedType findAspectDeclaringParents(DeclareParents p) { Set<ResolvedType> keys = this.members.keySet(); - for (Iterator<ResolvedType> iter = keys.iterator(); iter.hasNext();) { - ResolvedType element = iter.next(); - for (Iterator i = members.get(element).getDeclareParents().iterator(); i.hasNext();) { - DeclareParents dp = (DeclareParents) i.next(); + for (ResolvedType element : keys) { + for (DeclareParents dp : members.get(element).getDeclareParents()) { if (dp.equals(p)) { return element; } @@ -428,8 +424,7 @@ public class CrosscuttingMembersSet { if (verificationList == null) { return; } - for (Iterator<IVerificationRequired> iter = verificationList.iterator(); iter.hasNext();) { - IVerificationRequired element = iter.next(); + for (IVerificationRequired element : verificationList) { element.verify(); } verificationList = null; @@ -440,8 +435,7 @@ public class CrosscuttingMembersSet { public void write(CompressingDataOutputStream stream) throws IOException { // stream.writeInt(serializationVersion); stream.writeInt(shadowMungers.size()); - for (Iterator iterator = shadowMungers.iterator(); iterator.hasNext();) { - ShadowMunger shadowMunger = (ShadowMunger) iterator.next(); + for (ShadowMunger shadowMunger : shadowMungers) { shadowMunger.write(stream); } // // private List /* ShadowMunger */shadowMungers = null; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Dump.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Dump.java index 0efd56782..6e48de0d2 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Dump.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Dump.java @@ -372,8 +372,7 @@ public class Dump { private void dumpCompilerMessages(IMessageHolder messageHolder) { println("---- Compiler Messages ---"); if (messageHolder != null) { - for (Iterator<IMessage> i = messageHolder.getUnmodifiableListView().iterator(); i.hasNext();) { - IMessage message = i.next(); + for (IMessage message : messageHolder.getUnmodifiableListView()) { println(message.toString()); } } else { @@ -419,8 +418,8 @@ public class Dump { return; } - for (int i = 0; i < array.length; i++) { - print.println(array[i]); + for (Object o : array) { + print.println(o); } } @@ -454,8 +453,7 @@ public class Dump { if (list == null || list.isEmpty()) { println(NULL_OR_EMPTY); } else { - for (Iterator i = list.iterator(); i.hasNext();) { - Object o = i.next(); + for (Object o : list) { if (o instanceof Exception) { println((Exception) o); } else { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Lint.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Lint.java index aab34b8f6..7307ab93c 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Lint.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Lint.java @@ -234,8 +234,8 @@ public class Lint { @SuppressWarnings("rawtypes") public void setFromProperties(Properties properties) { - for (Iterator i = properties.entrySet().iterator(); i.hasNext();) { - Map.Entry entry = (Map.Entry) i.next(); + for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) { + Map.Entry entry = (Map.Entry) objectObjectEntry; Kind kind = kinds.get(entry.getKey()); if (kind == null) { MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR, entry.getKey())); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MemberImpl.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MemberImpl.java index fbf497ed2..9e608c9ad 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MemberImpl.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MemberImpl.java @@ -127,8 +127,8 @@ public class MemberImpl implements Member { public static String typesToSignature(UnresolvedType[] paramTypes) { StringBuffer buf = new StringBuffer(); buf.append("("); - for (int i = 0; i < paramTypes.length; i++) { - buf.append(paramTypes[i].getSignature()); + for (UnresolvedType paramType : paramTypes) { + buf.append(paramType.getSignature()); } buf.append(")"); return buf.toString(); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MethodDelegateTypeMunger.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MethodDelegateTypeMunger.java index bf8a76529..d07d8456f 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MethodDelegateTypeMunger.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/MethodDelegateTypeMunger.java @@ -114,8 +114,7 @@ public class MethodDelegateTypeMunger extends ResolvedTypeMunger { public ResolvedMember getDelegateFactoryMethod(World w) { ResolvedType aspectType = w.resolve(aspect); ResolvedMember[] methods = aspectType.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - ResolvedMember rm = methods[i]; + for (ResolvedMember rm : methods) { if (rm.getName().equals(factoryMethodName) && rm.getSignature().equals(factoryMethodSignature)) { return rm; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ReferenceType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ReferenceType.java index 7dc162a16..aad9a1dbe 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ReferenceType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ReferenceType.java @@ -225,8 +225,8 @@ public class ReferenceType extends ResolvedType { return true; } if (annotationTypes != null) { - for (int i = 0; i < annotationTypes.length; i++) { - if (annotationTypes[i].equals(ofType)) { + for (ResolvedType annotationType : annotationTypes) { + if (annotationType.equals(ofType)) { return true; } } @@ -278,17 +278,17 @@ public class ReferenceType extends ResolvedType { public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) { AnnotationAJ[] axs = getDelegate().getAnnotations(); if (axs != null) { - for (int i = 0; i < axs.length; i++) { - if (axs[i].getTypeSignature().equals(ofType.getSignature())) { - return axs[i]; + for (AnnotationAJ ax : axs) { + if (ax.getTypeSignature().equals(ofType.getSignature())) { + return ax; } } } if (annotations != null) { String searchSig = ofType.getSignature(); - for (int i = 0; i < annotations.length; i++) { - if (annotations[i].getTypeSignature().equals(searchSig)) { - return annotations[i]; + for (AnnotationAJ annotation : annotations) { + if (annotation.getTypeSignature().equals(searchSig)) { + return annotation; } } } @@ -386,9 +386,9 @@ public class ReferenceType extends ResolvedType { // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = other.getDeclaredMethods(); - for (int ai = 0, alen = a.length; ai < alen; ai++) { - for (int bi = 0, blen = b.length; bi < blen; bi++) { - if (!b[bi].isCompatibleWith(a[ai])) { + for (ResolvedMember member : a) { + for (ResolvedMember resolvedMember : b) { + if (!resolvedMember.isCompatibleWith(member)) { return false; } } @@ -507,11 +507,11 @@ public class ReferenceType extends ResolvedType { if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) { boolean wildcardsAllTheWay = true; ResolvedType[] myParameters = this.getResolvedTypeParameters(); - for (int i = 0; i < myParameters.length; i++) { - if (!myParameters[i].isGenericWildcard()) { + for (ResolvedType myParameter : myParameters) { + if (!myParameter.isGenericWildcard()) { wildcardsAllTheWay = false; } else { - BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i]; + BoundedReferenceType boundedRT = (BoundedReferenceType) myParameter; if (boundedRT.isExtends() || boundedRT.isSuper()) { wildcardsAllTheWay = false; } @@ -910,8 +910,8 @@ public class ReferenceType extends ResolvedType { public TypeVariable[] getTypeVariables() { if (typeVariables == null) { typeVariables = getDelegate().getTypeVariables(); - for (int i = 0; i < this.typeVariables.length; i++) { - typeVariables[i].resolve(world); + for (TypeVariable typeVariable : this.typeVariables) { + typeVariable.resolve(world); } } return typeVariables; @@ -1131,8 +1131,8 @@ public class ReferenceType extends ResolvedType { ret.append(PARAMETERIZED_TYPE_IDENTIFIER); ret.append(rawSignature.substring(1, rawSignature.length() - 1)); ret.append("<"); - for (int i = 0; i < someParameters.length; i++) { - ret.append(someParameters[i].getSignature()); + for (ResolvedType someParameter : someParameters) { + ret.append(someParameter.getSignature()); } ret.append(">;"); return ret.toString(); @@ -1144,18 +1144,18 @@ public class ReferenceType extends ResolvedType { String rawSig = aGenericType.getErasureSignature(); ret.append(rawSig.substring(0, rawSig.length() - 1)); ret.append("<"); - for (int i = 0; i < someParameters.length; i++) { - if (someParameters[i] instanceof ReferenceType) { - ret.append(((ReferenceType) someParameters[i]) + for (UnresolvedType someParameter : someParameters) { + if (someParameter instanceof ReferenceType) { + ret.append(((ReferenceType) someParameter) .getSignatureForAttribute()); - } else if (someParameters[i] instanceof Primitive) { - ret.append(((Primitive) someParameters[i]) + } else if (someParameter instanceof Primitive) { + ret.append(((Primitive) someParameter) .getSignatureForAttribute()); } else { throw new IllegalStateException( "DebugFor325731: expected a ReferenceType or Primitive but was " - + someParameters[i] + " of type " - + someParameters[i].getClass().getName()); + + someParameter + " of type " + + someParameter.getClass().getName()); } } ret.append(">;"); @@ -1200,8 +1200,8 @@ public class ReferenceType extends ResolvedType { } else { ResolvedType[] existing = getDelegate().getDeclaredInterfaces(); if (existing != null) { - for (int i = 0; i < existing.length; i++) { - if (existing[i].equals(newParent)) { + for (ResolvedType resolvedType : existing) { + if (resolvedType.equals(newParent)) { return; // already has this interface } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedMemberImpl.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedMemberImpl.java index 84e382422..90fd3ece3 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedMemberImpl.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedMemberImpl.java @@ -289,8 +289,8 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso return backingGenericMember.hasAnnotation(ofType); } if (annotationTypes != null) { - for (int i = 0, max = annotationTypes.length; i < max; i++) { - if (annotationTypes[i].equals(ofType)) { + for (ResolvedType annotationType : annotationTypes) { + if (annotationType.equals(ofType)) { return true; } } @@ -434,8 +434,8 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso s.writeByte(0); } else { s.writeByte(typeVariables.length); - for (int i = 0; i < typeVariables.length; i++) { - typeVariables[i].write(s); + for (TypeVariable typeVariable : typeVariables) { + typeVariable.write(s); } } String gsig = getGenericSignature(); @@ -445,11 +445,11 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso s.writeByte(0xff); } else { s.writeByte(parameterTypes.length); - for (int i = 0; i < parameterTypes.length; i++) { + for (UnresolvedType parameterType : parameterTypes) { if (s.canCompress()) { - s.writeCompressedSignature(parameterTypes[i].getSignature()); + s.writeCompressedSignature(parameterType.getSignature()); } else { - UnresolvedType array_element = parameterTypes[i]; + UnresolvedType array_element = parameterType; array_element.write(s); } } @@ -471,16 +471,16 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso StringBuffer sb = new StringBuffer(); if (typeVariables != null) { sb.append("<"); - for (int i = 0; i < typeVariables.length; i++) { - sb.append(typeVariables[i].getSignatureForAttribute()); // need + for (TypeVariable typeVariable : typeVariables) { + sb.append(typeVariable.getSignatureForAttribute()); // need // a // 'getSignatureForAttribute()' } sb.append(">"); } sb.append("("); - for (int i = 0; i < parameterTypes.length; i++) { - ResolvedType ptype = (ResolvedType) parameterTypes[i]; + for (UnresolvedType parameterType : parameterTypes) { + ResolvedType ptype = (ResolvedType) parameterType; sb.append(ptype.getSignatureForAttribute()); } sb.append(")"); @@ -492,14 +492,13 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso StringBuffer sb = new StringBuffer(); if (typeVariables != null) { sb.append("<"); - for (int i = 0; i < typeVariables.length; i++) { - sb.append(typeVariables[i].getSignature()); + for (TypeVariable typeVariable : typeVariables) { + sb.append(typeVariable.getSignature()); } sb.append(">"); } sb.append("("); - for (int i = 0; i < parameterTypes.length; i++) { - UnresolvedType ptype = parameterTypes[i]; + for (UnresolvedType ptype : parameterTypes) { sb.append(ptype.getSignature()); } sb.append(")"); @@ -509,8 +508,8 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso public static void writeArray(ResolvedMember[] members, CompressingDataOutputStream s) throws IOException { s.writeInt(members.length); - for (int i = 0, len = members.length; i < len; i++) { - members[i].write(s); + for (ResolvedMember member : members) { + member.write(s); } } @@ -1058,8 +1057,8 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso } StringBuffer sig = new StringBuffer(); UnresolvedType[] myParameterTypes = getGenericParameterTypes(); - for (int i = 0; i < myParameterTypes.length; i++) { - appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig, new HashSet<UnresolvedType>()); + for (UnresolvedType myParameterType : myParameterTypes) { + appendSigWithTypeVarBoundsRemoved(myParameterType, sig, new HashSet<UnresolvedType>()); } myParameterSignatureWithBoundsRemoved = sig.toString(); return myParameterSignatureWithBoundsRemoved; @@ -1239,9 +1238,9 @@ public class ResolvedMemberImpl extends MemberImpl implements IHasPosition, Reso public TypeVariable getTypeVariableNamed(String name) { // Check locally... if (typeVariables != null) { - for (int i = 0; i < typeVariables.length; i++) { - if (typeVariables[i].getName().equals(name)) { - return typeVariables[i]; + for (TypeVariable typeVariable : typeVariables) { + if (typeVariable.getName().equals(name)) { + return typeVariable; } } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedType.java index 98400ebdc..a5a5eea5d 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/ResolvedType.java @@ -437,8 +437,8 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - ResolvedType iface = interfaces[i]; + for (ResolvedType anInterface : interfaces) { + ResolvedType iface = anInterface; if (!genericsAware && iface.isParameterizedOrGenericType()) { iface = iface.getRawType(); } @@ -487,8 +487,8 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl } // Go through the interfaces on the way back down ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - ResolvedType iface = interfaces[i]; + for (ResolvedType anInterface : interfaces) { + ResolvedType iface = anInterface; if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) { iface = iface.getRawType(); } @@ -562,8 +562,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl if (!type.isMissing()) { ResolvedMember[] methods = type.getDeclaredMethods(); if (methods != null) { - for (int i = 0; i < methods.length; i++) { - ResolvedMember method = methods[i]; + for (ResolvedMember method : methods) { if (matches(method, m)) { return method; } @@ -584,8 +583,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl // Queue any interfaces not already checked: ResolvedType[] superinterfaces = type.getDeclaredInterfaces(); if (superinterfaces != null) { - for (int i = 0; i < superinterfaces.length; i++) { - ResolvedType interf = superinterfaces[i]; + for (ResolvedType interf : superinterfaces) { if (!typesTolookat.contains(interf)) { typesTolookat.add(interf); } @@ -612,8 +610,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl * return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { - for (int i = 0; i < a.length; i++) { - ResolvedMember f = a[i]; + for (ResolvedMember f : a) { if (matches(f, m)) { return f; } @@ -833,8 +830,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl while (typeIterator.hasNext()) { ResolvedType ty = typeIterator.next(); // System.out.println("super: " + ty + ", " + ); - for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) { - Declare dec = i.next(); + for (Declare dec : ty.getDeclares()) { if (dec.isAdviceLike()) { if (includeAdviceLike) { ret.add(dec); @@ -1031,8 +1027,8 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl methods = getGenericType().getDeclaredMethods(); } Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap(); - for (int i = 0, len = methods.length; i < len; i++) { - ShadowMunger munger = methods[i].getAssociatedShadowMunger(); + for (ResolvedMember method : methods) { + ShadowMunger munger = method.getAssociatedShadowMunger(); if (munger != null) { if (ajMembersNeedParameterization()) { // munger.setPointcut(munger.getPointcut().parameterizeWith( @@ -1041,7 +1037,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl if (munger instanceof Advice) { Advice advice = (Advice) munger; // update to use the parameterized signature... - UnresolvedType[] ptypes = methods[i].getGenericParameterTypes(); + UnresolvedType[] ptypes = method.getGenericParameterTypes(); UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length]; for (int j = 0; j < ptypes.length; j++) { if (ptypes[j] instanceof TypeVariableReferenceType) { @@ -1081,9 +1077,9 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List<ResolvedMember> l = new ArrayList<ResolvedMember>(); - for (int i = 0, len = ms.length; i < len; i++) { - if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { - l.add(ms[i]); + for (ResolvedMember m : ms) { + if (!m.isAjSynthetic() && m.getAssociatedShadowMunger() == null) { + l.add(m); } } return l.toArray(new ResolvedMember[l.size()]); @@ -1398,8 +1394,8 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl if (ret == null) { // try interfaces then, but only ITDs now... ResolvedType[] superInterfaces = onType.getDeclaredInterfaces(); - for (int i = 0; i < superInterfaces.length; i++) { - ret = superInterfaces[i].lookupMethodInITDs(member); + for (ResolvedType superInterface : superInterfaces) { + ret = superInterface.lookupMethodInITDs(member); if (ret != null) { return ret; } @@ -1646,8 +1642,7 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl } ResolvedType[] superIs = getDeclaredInterfaces(); - for (int i = 0; i < superIs.length; i++) { - ResolvedType superI = superIs[i]; + for (ResolvedType superI : superIs) { if (superI.genericTypeEquals(lookingFor)) { return superI; } @@ -2128,17 +2123,18 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl ResolvedType runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedType error = world.resolve("java.lang.Error"); - outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) { + outer: + for (ResolvedType childException : childExceptions) { // System.err.println("checking: " + childExceptions[i]); - if (runtimeException.isAssignableFrom(childExceptions[i])) { + if (runtimeException.isAssignableFrom(childException)) { continue; } - if (error.isAssignableFrom(childExceptions[i])) { + if (error.isAssignableFrom(childException)) { continue; } - for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { - if (parentExceptions[j].isAssignableFrom(childExceptions[i])) { + for (ResolvedType parentException : parentExceptions) { + if (parentException.isAssignableFrom(childException)) { continue outer; } } @@ -2439,9 +2435,9 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl } private void addPointcutsResolvingConflicts(List<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) { - for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) { - ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); - for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) { + for (ResolvedMember resolvedMember : added) { + ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) resolvedMember; + for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext(); ) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (toAdd == null || existing == null || existing == toAdd) { continue; @@ -2527,8 +2523,8 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl return this; } boolean workToDo = false; - for (int i = 0; i < typeParameters.length; i++) { - if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType) || typeParameters[i].isParameterizedType()) { + for (UnresolvedType typeParameter : typeParameters) { + if (typeParameter.isTypeVariableReference() || (typeParameter instanceof BoundedReferenceType) || typeParameter.isParameterizedType()) { workToDo = true; } } @@ -2720,22 +2716,22 @@ public abstract class ResolvedType extends UnresolvedType implements AnnotatedEl return false; } - for (int i = 0; i < typeParameters.length; i++) { - ResolvedType aType = (ResolvedType) typeParameters[i]; + for (UnresolvedType typeParameter : typeParameters) { + ResolvedType aType = (ResolvedType) typeParameter; if (aType.isTypeVariableReference() - // Changed according to the problems covered in bug 222648 - // Don't care what kind of type variable - the fact that there - // is one - // at all means we can't risk caching it against we get confused - // later - // by another variation of the parameterization that just - // happens to - // use the same type variable name - - // assume the worst - if its definetly not a type declared one, - // it could be anything - // && ((TypeVariableReference)aType).getTypeVariable(). - // getDeclaringElementKind()!=TypeVariable.TYPE + // Changed according to the problems covered in bug 222648 + // Don't care what kind of type variable - the fact that there + // is one + // at all means we can't risk caching it against we get confused + // later + // by another variation of the parameterization that just + // happens to + // use the same type variable name + + // assume the worst - if its definetly not a type declared one, + // it could be anything + // && ((TypeVariableReference)aType).getTypeVariable(). + // getDeclaringElementKind()!=TypeVariable.TYPE ) { parameterizedWithTypeVariable = FuzzyBoolean.YES; return true; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Shadow.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Shadow.java index cde7e5163..fc2b1d4d1 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Shadow.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Shadow.java @@ -350,11 +350,11 @@ public abstract class Shadow { */ public static int howMany(int i) { int count = 0; - for (int j = 0; j < SHADOW_KINDS.length; j++) { - if ((i & SHADOW_KINDS[j].bit) != 0) { - count++; - } - } + for (Kind shadowKind : SHADOW_KINDS) { + if ((i & shadowKind.bit) != 0) { + count++; + } + } return count; } @@ -487,11 +487,11 @@ public abstract class Shadow { */ protected boolean checkMunger(ShadowMunger munger) { if (munger.mustCheckExceptions()) { - for (Iterator<ResolvedType> i = munger.getThrownExceptions().iterator(); i.hasNext();) { - if (!checkCanThrow(munger, i.next())) { - return false; - } - } + for (ResolvedType resolvedType : munger.getThrownExceptions()) { + if (!checkCanThrow(munger, resolvedType)) { + return false; + } + } } return true; } @@ -522,11 +522,11 @@ public abstract class Shadow { private boolean isDeclaredException(ResolvedType resolvedTypeX, Member member) { ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld())); - for (int i = 0, len = excs.length; i < len; i++) { - if (excs[i].isAssignableFrom(resolvedTypeX)) { - return true; - } - } + for (ResolvedType exc : excs) { + if (exc.isAssignableFrom(resolvedTypeX)) { + return true; + } + } return false; } @@ -608,13 +608,12 @@ public abstract class Shadow { } } } - for (Iterator<String> iter = clashingAspects.iterator(); iter.hasNext();) { - String element = iter.next(); - String aspect1 = element.substring(0, element.indexOf(":")); - String aspect2 = element.substring(element.indexOf(":") + 1); - getIWorld().getLint().unorderedAdviceAtShadow.signal(new String[] { this.toString(), aspect1, aspect2 }, - this.getSourceLocation(), null); - } + for (String element : clashingAspects) { + String aspect1 = element.substring(0, element.indexOf(":")); + String aspect2 = element.substring(element.indexOf(":") + 1); + getIWorld().getLint().unorderedAdviceAtShadow.signal(new String[]{this.toString(), aspect1, aspect2}, + this.getSourceLocation(), null); + } } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/SignatureUtils.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/SignatureUtils.java index d32f7d99f..b88084a47 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/SignatureUtils.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/SignatureUtils.java @@ -219,8 +219,8 @@ public class SignatureUtils { if (types == null) return ""; StringBuffer buf = new StringBuffer(); - for (int i = 0, len = types.length; i < len; i++) { - buf.append(makeString(types[i])); + for (UnresolvedType type : types) { + buf.append(makeString(type)); buf.append(':'); } return buf.toString(); @@ -230,8 +230,8 @@ public class SignatureUtils { if (names == null) return ""; StringBuffer buf = new StringBuffer(); - for (int i = 0, len = names.length; i < len; i++) { - buf.append(names[i]); + for (String name : names) { + buf.append(name); buf.append(':'); } return buf.toString(); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/StandardAnnotation.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/StandardAnnotation.java index 475b0977f..5c898552d 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/StandardAnnotation.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/StandardAnnotation.java @@ -81,8 +81,7 @@ public class StandardAnnotation extends AbstractAnnotationAJ { if (nvPairs == null) { return false; } - for (int i = 0; i < nvPairs.size(); i++) { - AnnotationNameValuePair pair = nvPairs.get(i); + for (AnnotationNameValuePair pair : nvPairs) { if (pair.getName().equals(n)) { return true; } @@ -97,8 +96,7 @@ public class StandardAnnotation extends AbstractAnnotationAJ { if (nvPairs == null) { return false; } - for (int i = 0; i < nvPairs.size(); i++) { - AnnotationNameValuePair pair = nvPairs.get(i); + for (AnnotationNameValuePair pair : nvPairs) { if (pair.getName().equals(n)) { if (pair.getValue().stringify().equals(v)) { return true; @@ -119,8 +117,8 @@ public class StandardAnnotation extends AbstractAnnotationAJ { ArrayAnnotationValue aav = (ArrayAnnotationValue) nvp.getValue(); AnnotationValue[] avs = aav.getValues(); Set<String> targets = new HashSet<String>(); - for (int i = 0; i < avs.length; i++) { - EnumAnnotationValue value = (EnumAnnotationValue)avs[i]; + for (AnnotationValue av : avs) { + EnumAnnotationValue value = (EnumAnnotationValue) av; targets.add(value.getValue()); } return targets; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeFactory.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeFactory.java index e565e5bc8..2a578e392 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeFactory.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeFactory.java @@ -366,8 +366,8 @@ public class TypeFactory { parameterizedSig.append(baseTypeSignature.substring(1, baseTypeSignature.length() - 1)); if (arguments.length > 0) { parameterizedSig.append("<"); - for (int i = 0; i < arguments.length; i++) { - parameterizedSig.append(arguments[i].getSignature()); + for (UnresolvedType argument : arguments) { + parameterizedSig.append(argument.getSignature()); } parameterizedSig.append(">"); } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariable.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariable.java index d67bbd8dc..d9bd8c50c 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariable.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariable.java @@ -113,9 +113,9 @@ public class TypeVariable { UnresolvedType declaring = (UnresolvedType) declaringElement; ReferenceType rd = (ReferenceType) declaring.resolve(world); TypeVariable[] tVars = rd.getTypeVariables(); - for (int i = 0; i < tVars.length; i++) { - if (tVars[i].getName().equals(getName())) { - resolvedTVar = tVars[i]; + for (TypeVariable tVar : tVars) { + if (tVar.getName().equals(getName())) { + resolvedTVar = tVar; break; } } @@ -123,9 +123,9 @@ public class TypeVariable { // look for type variable on method... ResolvedMember declaring = (ResolvedMember) declaringElement; TypeVariable[] tvrts = declaring.getTypeVariables(); - for (int i = 0; i < tvrts.length; i++) { - if (tvrts[i].getName().equals(getName())) { - resolvedTVar = tvrts[i]; + for (TypeVariable tvrt : tvrts) { + if (tvrt.getName().equals(getName())) { + resolvedTVar = tvrt; // if (tvrts[i].isTypeVariableReference()) { // TypeVariableReferenceType tvrt = (TypeVariableReferenceType) tvrts[i].resolve(inSomeWorld); // TypeVariable tv = tvrt.getTypeVariable(); @@ -187,8 +187,8 @@ public class TypeVariable { return false; } // candidate is a subtype of all superInterfaces - for (int i = 0; i < superInterfaces.length; i++) { - if (!isASubtypeOf(superInterfaces[i], candidate)) { + for (UnresolvedType superInterface : superInterfaces) { + if (!isASubtypeOf(superInterface, candidate)) { return false; } } @@ -230,10 +230,10 @@ public class TypeVariable { ret.append(" extends "); ret.append(getFirstBound().getName()); if (superInterfaces != null) { - for (int i = 0; i < superInterfaces.length; i++) { - if (!getFirstBound().equals(superInterfaces[i])) { + for (UnresolvedType superInterface : superInterfaces) { + if (!getFirstBound().equals(superInterface)) { ret.append(" & "); - ret.append(superInterfaces[i].getName()); + ret.append(superInterface.getName()); } } } @@ -258,9 +258,9 @@ public class TypeVariable { sb.append(superclass.getSignature()); } if (superInterfaces.length != 0) { - for (int i = 0; i < superInterfaces.length; i++) { + for (UnresolvedType superInterface : superInterfaces) { sb.append(":"); - UnresolvedType iBound = superInterfaces[i]; + UnresolvedType iBound = superInterface; sb.append(iBound.getSignature()); } } @@ -278,9 +278,9 @@ public class TypeVariable { sb.append(((ReferenceType)superclass).getSignatureForAttribute()); } if (superInterfaces.length != 0) { - for (int i = 0; i < superInterfaces.length; i++) { + for (UnresolvedType superInterface : superInterfaces) { sb.append(":"); - ResolvedType iBound = (ResolvedType) superInterfaces[i]; + ResolvedType iBound = (ResolvedType) superInterface; sb.append(iBound.getSignatureForAttribute()); } } @@ -325,8 +325,7 @@ public class TypeVariable { s.writeInt(0); } else { s.writeInt(superInterfaces.length); - for (int i = 0; i < superInterfaces.length; i++) { - UnresolvedType ibound = superInterfaces[i]; + for (UnresolvedType ibound : superInterfaces) { ibound.write(s); } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariableReferenceType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariableReferenceType.java index 1e867ab5e..43c3b5cdd 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariableReferenceType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/TypeVariableReferenceType.java @@ -100,11 +100,11 @@ public class TypeVariableReferenceType extends ReferenceType implements TypeVari typeVariable.resolve(world); ResolvedType annotationType = ResolvedType.ANNOTATION.resolve(world); UnresolvedType[] ifBounds = typeVariable.getSuperInterfaces();// AdditionalBounds(); - for (int i = 0; i < ifBounds.length; i++) { - if (((ReferenceType) ifBounds[i]).isAnnotation()) { + for (UnresolvedType ifBound : ifBounds) { + if (((ReferenceType) ifBound).isAnnotation()) { return true; } - if (ifBounds[i].equals(annotationType)) { + if (ifBound.equals(annotationType)) { return true; // annotation itself does not have the annotation flag set in Java! } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/UnresolvedType.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/UnresolvedType.java index 0be8e3900..155bc0955 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/UnresolvedType.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/UnresolvedType.java @@ -875,12 +875,11 @@ public class UnresolvedType implements Traceable, TypeVariableDeclaringElement { if (vars == null || vars.length == 0) { return null; } - for (int i = 0; i < vars.length; i++) { - TypeVariable aVar = vars[i]; - if (aVar.getName().equals(name)) { - return aVar; - } - } + for (TypeVariable aVar : vars) { + if (aVar.getName().equals(name)) { + return aVar; + } + } return null; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Utils.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Utils.java index 8053af0c0..501ffa418 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Utils.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/Utils.java @@ -25,12 +25,12 @@ public class Utils { return false; } // Go through the annotation types on the advice - for (int i = 0; i < anns.length; i++) { - if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getTypeSignature())) { + for (AnnotationAJ ann : anns) { + if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(ann.getTypeSignature())) { // Two possibilities: // 1. there are no values specified (i.e. @SuppressAjWarnings) // 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"}) - String value = anns[i].getStringFormOfValue("value"); + String value = ann.getStringFormOfValue("value"); // Slightly lazy, just doing a string indexof if (value == null || value.indexOf(lintkey) != -1) { return true; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPatternList.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPatternList.java index 0b93b48d1..2cc737347 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPatternList.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPatternList.java @@ -42,8 +42,8 @@ public class AnnotationPatternList extends PatternNode { public AnnotationPatternList(AnnotationTypePattern[] arguments) { this.typePatterns = arguments; - for (int i = 0; i < arguments.length; i++) { - if (arguments[i] == AnnotationTypePattern.ELLIPSIS) { + for (AnnotationTypePattern argument : arguments) { + if (argument == AnnotationTypePattern.ELLIPSIS) { ellipsisCount++; } } @@ -68,8 +68,8 @@ public class AnnotationPatternList extends PatternNode { } public void resolve(World inWorld) { - for (int i = 0; i < typePatterns.length; i++) { - typePatterns[i].resolve(inWorld); + for (AnnotationTypePattern typePattern : typePatterns) { + typePattern.resolve(inWorld); } } @@ -85,11 +85,11 @@ public class AnnotationPatternList extends PatternNode { // now work through the args and the patterns, skipping at ellipsis FuzzyBoolean ret = FuzzyBoolean.YES; int argsIndex = 0; - for (int i = 0; i < typePatterns.length; i++) { - if (typePatterns[i] == AnnotationTypePattern.ELLIPSIS) { + for (AnnotationTypePattern typePattern : typePatterns) { + if (typePattern == AnnotationTypePattern.ELLIPSIS) { // match ellipsisMatchCount args argsIndex += numArgsMatchedByEllipsis; - } else if (typePatterns[i] == AnnotationTypePattern.ANY) { + } else if (typePattern == AnnotationTypePattern.ANY) { argsIndex++; } else { // match the argument type at argsIndex with the ExactAnnotationTypePattern @@ -97,7 +97,7 @@ public class AnnotationPatternList extends PatternNode { if (someArgs[argsIndex].isPrimitiveType()) { return FuzzyBoolean.NO; // can never match } - ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern) typePatterns[i]; + ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern) typePattern; FuzzyBoolean matches = ap.matchesRuntimeType(someArgs[argsIndex]); if (matches == FuzzyBoolean.NO) { return FuzzyBoolean.MAYBE; // could still match at runtime @@ -175,8 +175,8 @@ public class AnnotationPatternList extends PatternNode { public int hashCode() { int result = 41; - for (int i = 0, len = typePatterns.length; i < len; i++) { - result = 37 * result + typePatterns[i].hashCode(); + for (AnnotationTypePattern typePattern : typePatterns) { + result = 37 * result + typePattern.hashCode(); } return result; } @@ -194,8 +194,8 @@ public class AnnotationPatternList extends PatternNode { public void write(CompressingDataOutputStream s) throws IOException { s.writeShort(typePatterns.length); - for (int i = 0; i < typePatterns.length; i++) { - typePatterns[i].write(s); + for (AnnotationTypePattern typePattern : typePatterns) { + typePattern.write(s); } writeLocation(s); } @@ -206,8 +206,8 @@ public class AnnotationPatternList extends PatternNode { public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); - for (int i = 0; i < typePatterns.length; i++) { - typePatterns[i].traverse(visitor, ret); + for (AnnotationTypePattern typePattern : typePatterns) { + typePattern.traverse(visitor, ret); } return ret; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPointcut.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPointcut.java index e829d3772..2f70523cd 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPointcut.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/AnnotationPointcut.java @@ -141,8 +141,8 @@ public class AnnotationPointcut extends NameBindingPointcut { if (kind == Shadow.FieldGet || kind == Shadow.FieldSet) { // FIXME asc should include supers with getInterTypeMungersIncludingSupers ? List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers(); - for (Iterator iter = mungers.iterator(); iter.hasNext();) { - ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) iter.next(); + for (Object munger : mungers) { + ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger; if (typeMunger.getMunger() instanceof NewFieldTypeMunger) { ResolvedMember fakerm = typeMunger.getSignature(); if (fakerm.equals(member)) { @@ -162,8 +162,7 @@ public class AnnotationPointcut extends NameBindingPointcut { private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); - for (int i = 0; i < decMethods.length; i++) { - ResolvedMember member = decMethods[i]; + for (ResolvedMember member : decMethods) { if (member.equals(ajcMethod)) { return member; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java index db612b8cd..f7351b5d7 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsAnnotationPointcut.java @@ -182,9 +182,9 @@ public class ArgsAnnotationPointcut extends NameBindingPointcut { public List<BindingPattern> getBindingAnnotationTypePatterns() { List<BindingPattern> l = new ArrayList<BindingPattern>(); AnnotationTypePattern[] pats = arguments.getAnnotationPatterns(); - for (int i = 0; i < pats.length; i++) { - if (pats[i] instanceof BindingAnnotationTypePattern) { - l.add((BindingPattern)pats[i]); + for (AnnotationTypePattern pat : pats) { + if (pat instanceof BindingAnnotationTypePattern) { + l.add((BindingPattern) pat); } } return l; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsPointcut.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsPointcut.java index 56b1a4dc5..98c78d54d 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsPointcut.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ArgsPointcut.java @@ -89,8 +89,8 @@ public class ArgsPointcut extends NameBindingPointcut { // want to ignore. if (shadow.getKind() == Shadow.AdviceExecution) { int numExtraArgs = 0; - for (int i = 0; i < argumentsToMatchAgainst.length; i++) { - String argumentSignature = argumentsToMatchAgainst[i].getSignature(); + for (ResolvedType resolvedType : argumentsToMatchAgainst) { + String argumentSignature = resolvedType.getSignature(); if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX) || argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) { numExtraArgs++; @@ -124,9 +124,9 @@ public class ArgsPointcut extends NameBindingPointcut { public List<BindingTypePattern> getBindingTypePatterns() { List<BindingTypePattern> l = new ArrayList<BindingTypePattern>(); TypePattern[] pats = arguments.getTypePatterns(); - for (int i = 0; i < pats.length; i++) { - if (pats[i] instanceof BindingTypePattern) { - l.add((BindingTypePattern)pats[i]); + for (TypePattern pat : pats) { + if (pat instanceof BindingTypePattern) { + l.add((BindingTypePattern) pat); } } return l; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/Bindings.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/Bindings.java index 4853dd049..3b095c467 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/Bindings.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/Bindings.java @@ -97,9 +97,9 @@ public class Bindings { public UnresolvedType[] getUsedFormalTypes() { UnresolvedType[] ret = new UnresolvedType[bindings.length]; int index = 0; - for (int i = 0, len = bindings.length; i < len; i++) { - if (bindings[i] != null) { - ret[index++] = ((BindingTypePattern) bindings[i]).getExactType(); + for (BindingPattern binding : bindings) { + if (binding != null) { + ret[index++] = ((BindingTypePattern) binding).getExactType(); } } UnresolvedType[] newRet = new UnresolvedType[index]; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java index 627b622eb..bef0d145c 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationFieldTypePattern.java @@ -106,8 +106,7 @@ public class ExactAnnotationFieldTypePattern extends ExactAnnotationTypePattern ResolvedMember[] annotationFields = theAnnotationType.getDeclaredMethods(); field = null; boolean looksAmbiguous = false; - for (int i = 0; i < annotationFields.length; i++) { - ResolvedMember resolvedMember = annotationFields[i]; + for (ResolvedMember resolvedMember : annotationFields) { if (resolvedMember.getReturnType().equals(formalBinding.getType())) { if (field != null) { boolean haveProblem = true; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java index b51d72df9..8105a4f1d 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExactAnnotationTypePattern.java @@ -220,11 +220,11 @@ public class ExactAnnotationTypePattern extends AnnotationTypePattern { if (parameterAnnotations == null) { return FuzzyBoolean.NO; } - for (int i = 0; i < parameterAnnotations.length; i++) { - if (annotationType.equals(parameterAnnotations[i])) { + for (ResolvedType parameterAnnotation : parameterAnnotations) { + if (annotationType.equals(parameterAnnotation)) { // Are we also matching annotation values? if (annotationValues != null) { - parameterAnnotations[i] + parameterAnnotation .getWorld() .getMessageHandler() .handleMessage( @@ -383,8 +383,7 @@ public class ExactAnnotationTypePattern extends AnnotationTypePattern { } else { s.writeInt(annotationValues.size()); Set<String> key = annotationValues.keySet(); - for (Iterator<String> keys = key.iterator(); keys.hasNext();) { - String k = keys.next(); + for (String k : key) { s.writeUTF(k); s.writeUTF(annotationValues.get(k)); } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExposedState.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExposedState.java index 2a9807118..8ff7849af 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExposedState.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/ExposedState.java @@ -53,8 +53,8 @@ public class ExposedState { } public boolean isFullySetUp() { - for (int i = 0; i < vars.length; i++) { - if (vars[i] == null) + for (Var var : vars) { + if (var == null) return false; } return true; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/HasMemberTypePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/HasMemberTypePattern.java index 2b1f28fd4..c84cf3eee 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/HasMemberTypePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/HasMemberTypePattern.java @@ -104,8 +104,7 @@ public class HasMemberTypePattern extends TypePattern { } // try itds before we give up (this doesnt find annotations - the signature returned may not include them) List<ConcreteTypeMunger> mungers = type.getInterTypeMungersIncludingSupers(); - for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) { - ConcreteTypeMunger munger = iter.next(); + for (ConcreteTypeMunger munger : mungers) { Member member = munger.getSignature(); if (signaturePattern.matches(member, type.getWorld(), false)) { if (!Modifier.isPublic(member.getModifiers())) { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/NamePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/NamePattern.java index 561b99197..52331d13e 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/NamePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/NamePattern.java @@ -32,8 +32,8 @@ public class NamePattern extends PatternNode { public NamePattern(char[] pattern) { this.pattern = pattern; - for (int i = 0, len = pattern.length; i < len; i++) { - if (pattern[i] == '*') { + for (char c : pattern) { + if (c == '*') { starCount++; } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/PointcutRewriter.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/PointcutRewriter.java index 81ff33bab..72e552ab4 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/PointcutRewriter.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/PointcutRewriter.java @@ -330,8 +330,7 @@ public class PointcutRewriter { SortedSet<Pointcut> nodes = new TreeSet<Pointcut>(new PointcutEvaluationExpenseComparator()); collectAndNodes(apc, nodes); // look for A and !A, or IfFalse - for (Iterator<Pointcut> iter = nodes.iterator(); iter.hasNext();) { - Pointcut element = iter.next(); + for (Pointcut element : nodes) { if (element instanceof NotPointcut) { Pointcut body = ((NotPointcut) element).getNegatedPointcut(); if (nodes.contains(body)) { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SignaturePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SignaturePattern.java index 365b5b7a7..4541d1579 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SignaturePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SignaturePattern.java @@ -140,8 +140,7 @@ public class SignaturePattern extends PatternNode implements ISignaturePattern { patternNode.traverse(visitor, null); if (visitor.containedIncorrectTargetKind()) { Set<ExactAnnotationTypePattern> keys = visitor.getIncorrectTargetKinds().keySet(); - for (Iterator<ExactAnnotationTypePattern> iter = keys.iterator(); iter.hasNext();) { - PatternNode node = iter.next(); + for (PatternNode node : keys) { AnnotationTargetKind[] targetKinds = visitor.getIncorrectTargetKinds().get(node); reportUnmatchedTargetKindMessage(targetKinds, node, scope, false); } @@ -208,12 +207,12 @@ public class SignaturePattern extends PatternNode implements ISignaturePattern { return data; } List<AnnotationTargetKind> incorrectTargets = new ArrayList<AnnotationTargetKind>(); - for (int i = 0; i < targetKinds.length; i++) { - if (targetKinds[i].getName().equals(kind.getName()) - || (targetKinds[i].getName().equals("PARAMETER") && node.isForParameterAnnotationMatch())) { + for (AnnotationTargetKind targetKind : targetKinds) { + if (targetKind.getName().equals(kind.getName()) + || (targetKind.getName().equals("PARAMETER") && node.isForParameterAnnotationMatch())) { return data; } - incorrectTargets.add(targetKinds[i]); + incorrectTargets.add(targetKind); } if (incorrectTargets.isEmpty()) { return data; @@ -227,8 +226,7 @@ public class SignaturePattern extends PatternNode implements ISignaturePattern { } // exception here is if parameter annotations are allowed if (parameterTargettingAnnotationsAllowed) { - for (int i = 0; i < targetKinds.length; i++) { - AnnotationTargetKind annotationTargetKind = targetKinds[i]; + for (AnnotationTargetKind annotationTargetKind : targetKinds) { if (annotationTargetKind.getName().equals("PARAMETER") && node.isForParameterAnnotationMatch()) { return data; } @@ -724,8 +722,7 @@ public class SignaturePattern extends PatternNode implements ISignaturePattern { private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); - for (int i = 0; i < decMethods.length; i++) { - ResolvedMember member = decMethods[i]; + for (ResolvedMember member : decMethods) { if (member.equals(ajcMethod)) { return member; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SimpleScope.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SimpleScope.java index 119103d84..1dfe1f6ec 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SimpleScope.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/SimpleScope.java @@ -40,8 +40,7 @@ public class SimpleScope implements IScope { } public UnresolvedType lookupType(String name, IHasPosition location) { - for (int i = 0; i < importedNames.length; i++) { - String importedName = importedNames[i]; + for (String importedName : importedNames) { // make sure we're matching against the type name rather than part of it // if (importedName.endsWith("." + name)) { if (importedName.endsWith(name)) { @@ -104,9 +103,9 @@ public class SimpleScope implements IScope { } public FormalBinding lookupFormal(String name) { - for (int i = 0, len = bindings.length; i < len; i++) { - if (bindings[i].getName().equals(name)) { - return bindings[i]; + for (FormalBinding binding : bindings) { + if (binding.getName().equals(name)) { + return binding; } } return null; diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternList.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternList.java index da9d6e15a..040d6dbe2 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternList.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternList.java @@ -51,8 +51,8 @@ public class TypePatternList extends PatternNode { public TypePatternList(TypePattern[] arguments) { this.typePatterns = arguments; - for (int i = 0; i < arguments.length; i++) { - if (arguments[i] == TypePattern.ELLIPSIS) { + for (TypePattern argument : arguments) { + if (argument == TypePattern.ELLIPSIS) { ellipsisCount++; } } @@ -452,8 +452,7 @@ public class TypePatternList extends PatternNode { } public void postRead(ResolvedType enclosingType) { - for (int i = 0; i < typePatterns.length; i++) { - TypePattern p = typePatterns[i]; + for (TypePattern p : typePatterns) { p.postRead(enclosingType); } } @@ -479,8 +478,8 @@ public class TypePatternList extends PatternNode { @Override public int hashCode() { int result = 41; - for (int i = 0, len = typePatterns.length; i < len; i++) { - result = 37 * result + typePatterns[i].hashCode(); + for (TypePattern typePattern : typePatterns) { + result = 37 * result + typePattern.hashCode(); } return result; } @@ -521,8 +520,8 @@ public class TypePatternList extends PatternNode { @Override public void write(CompressingDataOutputStream s) throws IOException { s.writeShort(typePatterns.length); - for (int i = 0; i < typePatterns.length; i++) { - typePatterns[i].write(s); + for (TypePattern typePattern : typePatterns) { + typePattern.write(s); } // writeLocation(s); } @@ -533,8 +532,8 @@ public class TypePatternList extends PatternNode { public List<UnresolvedType> getExactTypes() { List<UnresolvedType> ret = new ArrayList<UnresolvedType>(); - for (int i = 0; i < typePatterns.length; i++) { - UnresolvedType t = typePatterns[i].getExactType(); + for (TypePattern typePattern : typePatterns) { + UnresolvedType t = typePattern.getExactType(); if (!ResolvedType.isMissing(t)) { ret.add(t); } @@ -550,15 +549,14 @@ public class TypePatternList extends PatternNode { @Override public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); - for (int i = 0; i < typePatterns.length; i++) { - typePatterns[i].traverse(visitor, ret); + for (TypePattern typePattern : typePatterns) { + typePattern.traverse(visitor, ret); } return ret; } public boolean areAllExactWithNoSubtypesAllowed() { - for (int i = 0; i < typePatterns.length; i++) { - TypePattern array_element = typePatterns[i]; + for (TypePattern array_element : typePatterns) { if (!(array_element instanceof ExactTypePattern)) { return false; } else { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternQuestions.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternQuestions.java index d4bdf2e58..8289d306e 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternQuestions.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypePatternQuestions.java @@ -37,11 +37,10 @@ public class TypePatternQuestions { } public Question anyChanges() { - for (Iterator<Map.Entry<Question,FuzzyBoolean>> i = questionsAndAnswers.entrySet().iterator(); i.hasNext(); ) { - Map.Entry<Question,FuzzyBoolean> entry = i.next(); - Question question = (Question)entry.getKey(); - FuzzyBoolean expectedAnswer = (FuzzyBoolean)entry.getValue(); - + for (Map.Entry<Question, FuzzyBoolean> entry : questionsAndAnswers.entrySet()) { + Question question = (Question) entry.getKey(); + FuzzyBoolean expectedAnswer = (FuzzyBoolean) entry.getValue(); + FuzzyBoolean currentAnswer = question.ask(); //System.out.println(question + ":" + currentAnswer); if (currentAnswer != expectedAnswer) { diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePattern.java index c2d4bd0ec..57377abb5 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePattern.java @@ -163,8 +163,8 @@ public class TypeVariablePattern extends PatternNode { hashCode = hashCode * 37 + lowerBound.hashCode(); } if (interfaceBounds != null) { - for (int i = 0; i < interfaceBounds.length; i++) { - hashCode = 37 * hashCode + interfaceBounds[i].hashCode(); + for (TypePattern interfaceBound : interfaceBounds) { + hashCode = 37 * hashCode + interfaceBound.hashCode(); } } return hashCode; @@ -207,8 +207,8 @@ public class TypeVariablePattern extends PatternNode { s.writeInt(0); } else { s.writeInt(interfaceBounds.length); - for (int i = 0; i < interfaceBounds.length; i++) { - interfaceBounds[i].write(s); + for (TypePattern interfaceBound : interfaceBounds) { + interfaceBound.write(s); } } s.writeBoolean(hasLowerBound()); diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePatternList.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePatternList.java index 7bbe67872..85dca44b4 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePatternList.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/TypeVariablePatternList.java @@ -35,9 +35,9 @@ public class TypeVariablePatternList extends PatternNode { } public TypeVariablePattern lookupTypeVariable(String name) { - for (int i = 0; i < patterns.length; i++) { - if (patterns[i].getName().equals(name)) { - return patterns[i]; + for (TypeVariablePattern pattern : patterns) { + if (pattern.getName().equals(name)) { + return pattern; } } return null; @@ -49,8 +49,8 @@ public class TypeVariablePatternList extends PatternNode { public void write(CompressingDataOutputStream s) throws IOException { s.writeInt(patterns.length); - for (int i = 0; i < patterns.length; i++) { - patterns[i].write(s); + for (TypeVariablePattern pattern : patterns) { + pattern.write(s); } writeLocation(s); } @@ -75,8 +75,8 @@ public class TypeVariablePatternList extends PatternNode { public Object traverse(PatternNodeVisitor visitor, Object data) { Object ret = accept(visitor, data); - for (int i = 0; i < patterns.length; i++) { - patterns[i].traverse(visitor, ret); + for (TypeVariablePattern pattern : patterns) { + pattern.traverse(visitor, ret); } return ret; } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java index 0941462d1..35f2dc674 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildAnnotationTypePattern.java @@ -93,8 +93,7 @@ public class WildAnnotationTypePattern extends AnnotationTypePattern { } String v = annotationValues.get(k); boolean validKey = false; - for (int i = 0; i < ms.length; i++) { - ResolvedMember resolvedMember = ms[i]; + for (ResolvedMember resolvedMember : ms) { if (resolvedMember.getName().equals(key) && resolvedMember.isAbstract()) { validKey = true; ResolvedType t = resolvedMember.getReturnType().resolve(scope.getWorld()); @@ -239,8 +238,8 @@ public class WildAnnotationTypePattern extends AnnotationTypePattern { // } // replacementValues.put(k, rt.getSignature()); } else { - scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.UNSUPPORTED_ANNOTATION_VALUE_TYPE,t), getSourceLocation())); - replacementValues.put(k,""); + scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.UNSUPPORTED_ANNOTATION_VALUE_TYPE, t), getSourceLocation())); + replacementValues.put(k, ""); } } } @@ -265,8 +264,8 @@ public class WildAnnotationTypePattern extends AnnotationTypePattern { } if (isForParameterAnnotationMatch()) { if (parameterAnnotations != null && parameterAnnotations.length != 0) { - for (int i = 0; i < parameterAnnotations.length; i++) { - if (typePattern.matches(parameterAnnotations[i], TypePattern.STATIC).alwaysTrue()) { + for (ResolvedType parameterAnnotation : parameterAnnotations) { + if (typePattern.matches(parameterAnnotation, TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } @@ -276,8 +275,8 @@ public class WildAnnotationTypePattern extends AnnotationTypePattern { // matched by the typePattern. ResolvedType[] annTypes = annotated.getAnnotationTypes(); if (annTypes != null && annTypes.length != 0) { - for (int i = 0; i < annTypes.length; i++) { - if (typePattern.matches(annTypes[i], TypePattern.STATIC).alwaysTrue()) { + for (ResolvedType annType : annTypes) { + if (typePattern.matches(annType, TypePattern.STATIC).alwaysTrue()) { return FuzzyBoolean.YES; } } @@ -368,8 +367,7 @@ public class WildAnnotationTypePattern extends AnnotationTypePattern { } else { s.writeInt(annotationValues.size()); Set<String> key = annotationValues.keySet(); - for (Iterator<String> keys = key.iterator(); keys.hasNext();) { - String k = keys.next(); + for (String k : key) { s.writeUTF(k); s.writeUTF(annotationValues.get(k)); } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildTypePattern.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildTypePattern.java index 9081c5c02..3dad2ce6b 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildTypePattern.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/patterns/WildTypePattern.java @@ -101,8 +101,8 @@ public class WildTypePattern extends TypePattern { this.namePatterns = namePatterns; this.dim = dim; ellipsisCount = 0; - for (int i = 0; i < namePatterns.length; i++) { - if (namePatterns[i] == NamePattern.ELLIPSIS) { + for (NamePattern namePattern : namePatterns) { + if (namePattern == NamePattern.ELLIPSIS) { ellipsisCount++; } } @@ -341,14 +341,13 @@ public class WildTypePattern extends TypePattern { // we've already ruled out "*", and no other name pattern should match an anonymous type return false; } - for (int i = 0, len = knownMatches.length; i < len; i++) { - if (knownMatches[i].equals(targetTypeName)) { + for (String knownMatch : knownMatches) { + if (knownMatch.equals(targetTypeName)) { return true; } } } else { - for (int i = 0, len = knownMatches.length; i < len; i++) { - String knownMatch = knownMatches[i]; + for (String knownMatch : knownMatches) { // String knownPrefix = knownMatches[i] + "$"; // if (targetTypeName.startsWith(knownPrefix)) { if (targetTypeName.startsWith(knownMatch) && targetTypeName.length() > knownMatch.length() @@ -363,8 +362,7 @@ public class WildTypePattern extends TypePattern { // if any prefixes match, strip the prefix and check that the rest matches // assumes that prefixes have a dot at the end - for (int i = 0, len = importedPrefixes.length; i < len; i++) { - String prefix = importedPrefixes[i]; + for (String prefix : importedPrefixes) { // System.err.println("prefix match? " + prefix + " to " + targetTypeName); if (targetTypeName.startsWith(prefix)) { @@ -965,8 +963,8 @@ public class WildTypePattern extends TypePattern { canCreateExactTypePattern = false; } if (additionalInterfaceBounds != null) { - for (int i = 0; i < additionalInterfaceBounds.length; i++) { - if (ResolvedType.isMissing(additionalInterfaceBounds[i].getExactType())) { + for (TypePattern additionalInterfaceBound : additionalInterfaceBounds) { + if (ResolvedType.isMissing(additionalInterfaceBound.getExactType())) { canCreateExactTypePattern = false; } } @@ -1012,9 +1010,9 @@ public class WildTypePattern extends TypePattern { int minRequiredTypeParameters = typeParameters.size(); boolean foundEllipsis = false; TypePattern[] typeParamPatterns = typeParameters.getTypePatterns(); - for (int i = 0; i < typeParamPatterns.length; i++) { - if (typeParamPatterns[i] instanceof WildTypePattern) { - WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i]; + for (TypePattern typeParamPattern : typeParamPatterns) { + if (typeParamPattern instanceof WildTypePattern) { + WildTypePattern wtp = (WildTypePattern) typeParamPattern; if (wtp.ellipsisCount > 0) { foundEllipsis = true; minRequiredTypeParameters--; @@ -1160,16 +1158,16 @@ public class WildTypePattern extends TypePattern { // if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS; List<String> ret = new ArrayList<String>(); - for (int i = 0, len = possibleMatches.length; i < len; i++) { - char[][] names = splitNames(possibleMatches[i], true); // ??? not most efficient + for (String possibleMatch : possibleMatches) { + char[][] names = splitNames(possibleMatch, true); // ??? not most efficient if (namePatterns[0].matches(names[names.length - 1])) { - ret.add(possibleMatches[i]); + ret.add(possibleMatch); continue; } - if (possibleMatches[i].indexOf("$") != -1) { - names = splitNames(possibleMatches[i], false); // ??? not most efficient + if (possibleMatch.indexOf("$") != -1) { + names = splitNames(possibleMatch, false); // ??? not most efficient if (namePatterns[0].matches(names[names.length - 1])) { - ret.add(possibleMatches[i]); + ret.add(possibleMatch); } } } @@ -1282,8 +1280,8 @@ public class WildTypePattern extends TypePattern { @Override public int hashCode() { int result = 17; - for (int i = 0, len = namePatterns.length; i < len; i++) { - result = 37 * result + namePatterns[i].hashCode(); + for (NamePattern namePattern : namePatterns) { + result = 37 * result + namePattern.hashCode(); } result = 37 * result + annotationPattern.hashCode(); if (upperBound != null) { @@ -1302,8 +1300,8 @@ public class WildTypePattern extends TypePattern { s.writeByte(TypePattern.WILD); s.writeByte(VERSION); s.writeShort(namePatterns.length); - for (int i = 0; i < namePatterns.length; i++) { - namePatterns[i].write(s); + for (NamePattern namePattern : namePatterns) { + namePattern.write(s); } s.writeBoolean(includeSubtypes); s.writeInt(dim); @@ -1327,8 +1325,8 @@ public class WildTypePattern extends TypePattern { } s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length); if (additionalInterfaceBounds != null) { - for (int i = 0; i < additionalInterfaceBounds.length; i++) { - additionalInterfaceBounds[i].write(s); + for (TypePattern additionalInterfaceBound : additionalInterfaceBounds) { + additionalInterfaceBound.write(s); } } } diff --git a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/tools/StandardPointcutParser.java b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/tools/StandardPointcutParser.java index e549325af..afc14188d 100644 --- a/org.aspectj.matcher/src/main/java/org/aspectj/weaver/tools/StandardPointcutParser.java +++ b/org.aspectj.matcher/src/main/java/org/aspectj/weaver/tools/StandardPointcutParser.java @@ -149,8 +149,8 @@ public class StandardPointcutParser { */ private StandardPointcutParser(Set/* <PointcutPrimitives> */supportedPointcutKinds, World world) { supportedPrimitives = supportedPointcutKinds; - for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) { - PointcutPrimitive element = (PointcutPrimitive) iter.next(); + for (Object supportedPointcutKind : supportedPointcutKinds) { + PointcutPrimitive element = (PointcutPrimitive) supportedPointcutKind; if ((element == PointcutPrimitive.IF) || (element == PointcutPrimitive.CFLOW) || (element == PointcutPrimitive.CFLOW_BELOW)) { throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives"); diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java index 532588363..4175425ef 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonAdvancedPointcutExpressionTests.java @@ -655,10 +655,10 @@ public abstract class CommonAdvancedPointcutExpressionTests extends TestCase { private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) { ResolvedMember[] methods = type.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(methodName) - && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) { - return methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals(methodName) + && (methodSignature == null || methodSignature.equals(method.getSignature()))) { + return method; } } return null; diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java index 8fccfbf99..02ad20f1f 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/matcher/tools/CommonPointcutExpressionTests.java @@ -738,11 +738,11 @@ public abstract class CommonPointcutExpressionTests extends TestCase { private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) { ResolvedMember[] methods = type.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - System.out.println(methods[i].getName() + methods[i].getSignature()); - if (methods[i].getName().equals(methodName) - && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) { - return methods[i]; + for (ResolvedMember method : methods) { + System.out.println(method.getName() + method.getSignature()); + if (method.getName().equals(methodName) + && (methodSignature == null || methodSignature.equals(method.getSignature()))) { + return method; } } return null; diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java index ff6c56a34..8998904a6 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/CommonWorldTests.java @@ -49,8 +49,7 @@ public abstract class CommonWorldTests extends TestCase { public void testPrimitiveTypes() { ResolvedType[] primitives = world.resolve(primitiveTypes); - for (int i = 0, len = primitives.length; i < len; i++) { - ResolvedType ty = primitives[i]; + for (ResolvedType ty : primitives) { modifiersTest(ty, Modifier.PUBLIC | Modifier.FINAL); fieldsTest(ty, ResolvedMember.NONE); methodsTest(ty, ResolvedMember.NONE); @@ -60,8 +59,7 @@ public abstract class CommonWorldTests extends TestCase { isInterfaceTest(ty, false); isClassTest(ty, false); isAspectTest(ty, false); - for (int j = 0; j < len; j++) { - ResolvedType ty1 = primitives[j]; + for (ResolvedType ty1 : primitives) { if (ty.equals(ty1)) { isCoerceableFromTest(ty, ty1, true); } else if (ty.equals(UnresolvedType.BOOLEAN) || ty1.equals(UnresolvedType.BOOLEAN) @@ -75,15 +73,15 @@ public abstract class CommonWorldTests extends TestCase { // Result of this depends on whether autoboxing is supported // isCoerceableFromTest(ty, UnresolvedType.OBJECT, getSupportsAutoboxing()); - primAssignTest("B", new String[] {}); - primAssignTest("S", new String[] { "B" }); - primAssignTest("C", new String[] { "B" }); - primAssignTest("I", new String[] { "B", "S", "C" }); - primAssignTest("J", new String[] { "B", "S", "C", "I" }); - primAssignTest("F", new String[] { "B", "S", "C", "I", "J" }); - primAssignTest("D", new String[] { "B", "S", "C", "I", "J", "F" }); - primAssignTest("Z", new String[] {}); - primAssignTest("V", new String[] {}); + primAssignTest("B", new String[]{}); + primAssignTest("S", new String[]{"B"}); + primAssignTest("C", new String[]{"B"}); + primAssignTest("I", new String[]{"B", "S", "C"}); + primAssignTest("J", new String[]{"B", "S", "C", "I"}); + primAssignTest("F", new String[]{"B", "S", "C", "I", "J"}); + primAssignTest("D", new String[]{"B", "S", "C", "I", "J", "F"}); + primAssignTest("Z", new String[]{}); + primAssignTest("V", new String[]{}); } } @@ -110,8 +108,7 @@ public abstract class CommonWorldTests extends TestCase { public void testPrimitiveArrays() { ResolvedType[] primitives = world.resolve(primitiveTypes); - for (int i = 0, len = primitives.length; i < len; i++) { - ResolvedType ty = primitives[i]; + for (ResolvedType ty : primitives) { UnresolvedType tx = UnresolvedType.forSignature("[" + ty.getSignature()); ResolvedType aty = world.resolve(tx, true); assertTrue("Couldnt find type " + tx, !aty.isMissing()); @@ -120,16 +117,15 @@ public abstract class CommonWorldTests extends TestCase { methodsTest(aty, ResolvedMember.NONE); interfaceTest( aty, - new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE), - world.getCoreType(UnresolvedType.SERIALIZABLE) }); + new ResolvedType[]{world.getCoreType(UnresolvedType.CLONEABLE), + world.getCoreType(UnresolvedType.SERIALIZABLE)}); superclassTest(aty, UnresolvedType.OBJECT); pointcutsTest(aty, ResolvedMember.NONE); isInterfaceTest(aty, false); isClassTest(aty, false); isAspectTest(aty, false); - for (int j = 0; j < len; j++) { - ResolvedType ty1 = primitives[j]; + for (ResolvedType ty1 : primitives) { isCoerceableFromTest(aty, ty1, false); tx = UnresolvedType.forSignature("[" + ty1.getSignature()); ResolvedType aty1 = getWorld().resolve(tx, true); @@ -144,8 +140,7 @@ public abstract class CommonWorldTests extends TestCase { } } // double dimension arrays - for (int i = 0, len = primitives.length; i < len; i++) { - ResolvedType ty = primitives[i]; + for (ResolvedType ty : primitives) { UnresolvedType tx = UnresolvedType.forSignature("[[" + ty.getSignature()); ResolvedType aty = world.resolve(tx, true); assertTrue("Couldnt find type " + tx, !aty.isMissing()); @@ -154,16 +149,15 @@ public abstract class CommonWorldTests extends TestCase { methodsTest(aty, ResolvedMember.NONE); interfaceTest( aty, - new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE), - world.getCoreType(UnresolvedType.SERIALIZABLE) }); + new ResolvedType[]{world.getCoreType(UnresolvedType.CLONEABLE), + world.getCoreType(UnresolvedType.SERIALIZABLE)}); superclassTest(aty, UnresolvedType.OBJECT); pointcutsTest(aty, ResolvedMember.NONE); isInterfaceTest(aty, false); isClassTest(aty, false); isAspectTest(aty, false); - for (int j = 0; j < len; j++) { - ResolvedType ty1 = primitives[j]; + for (ResolvedType ty1 : primitives) { isCoerceableFromTest(aty, ty1, false); tx = UnresolvedType.forSignature("[[" + ty1.getSignature()); ResolvedType aty1 = getWorld().resolve(tx, true); @@ -201,15 +195,15 @@ public abstract class CommonWorldTests extends TestCase { protected void interfaceTest(ResolvedType type, ResolvedType[] expectedInterfaces) { ResolvedType[] interfaces = type.getDeclaredInterfaces(); - for (int i = 0; i < expectedInterfaces.length; i++) { + for (ResolvedType expectedInterface : expectedInterfaces) { boolean wasMissing = true; - for (int j = 0; j < interfaces.length; j++) { - if (interfaces[j].getSignature().equals(expectedInterfaces[i].getSignature())) { + for (ResolvedType anInterface : interfaces) { + if (anInterface.getSignature().equals(expectedInterface.getSignature())) { wasMissing = false; } } if (wasMissing) { - fail("Expected declared interface " + expectedInterfaces[i] + " but it wasn't found in " + fail("Expected declared interface " + expectedInterface + " but it wasn't found in " + Arrays.asList(interfaces)); } } diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java index 665f4bdda..2b0e01888 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/DumpPointcutVisitor.java @@ -549,8 +549,8 @@ public class DumpPointcutVisitor implements PatternNodeVisitor { "(if(true) && set(int BaseApp.i))" }; - for (int i = 0; i < s.length; i++) { - check(s[i]); + for (String value : s) { + check(value); } } diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java index 265ee4b0a..8c8a89035 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/ModifiersPatternTestCase.java @@ -64,9 +64,9 @@ public class ModifiersPatternTestCase extends PatternsTestCase { } private void checkMatch(ModifiersPattern p, int[] matches, boolean shouldMatch) { - for (int i = 0; i < matches.length; i++) { - boolean result = p.matches(matches[i]); - String msg = "matches " + p + " to " + Modifier.toString(matches[i]) + " expected "; + for (int match : matches) { + boolean result = p.matches(match); + String msg = "matches " + p + " to " + Modifier.toString(match) + " expected "; if (shouldMatch) { assertTrue(msg + shouldMatch, result); } else { @@ -78,8 +78,8 @@ public class ModifiersPatternTestCase extends PatternsTestCase { public void testSerialization() throws IOException { String[] patterns = new String[] { "", "!public", "public", "public static", "private !static !strictfp", }; - for (int i = 0, len = patterns.length; i < len; i++) { - checkSerialization(patterns[i]); + for (String pattern : patterns) { + checkSerialization(pattern); } } diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java index fe3b0f2d4..f1bec0837 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternParserTestCase.java @@ -59,8 +59,7 @@ public class NamePatternParserTestCase extends TestCase { * @param b */ private void checkMatch(String[] patterns) { - for (int i = 0, len = patterns.length; i < len; i++) { - String pattern = patterns[i]; + for (String pattern : patterns) { ITokenSource tokenSource = BasicTokenSource.makeTokenSource( pattern, null); NamePattern p1 = new PatternParser(tokenSource).parseNamePattern(); diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java index e1876cc3b..d26395038 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/NamePatternTestCase.java @@ -64,8 +64,8 @@ public class NamePatternTestCase extends TestCase { * @param b */ private void checkMatch(String string, String[] patterns, boolean shouldMatch) { - for (int i = 0, len = patterns.length; i < len; i++) { - NamePattern p = new NamePattern(patterns[i]); + for (String pattern : patterns) { + NamePattern p = new NamePattern(pattern); checkMatch(string, p, shouldMatch); } } @@ -82,8 +82,8 @@ public class NamePatternTestCase extends TestCase { } private void checkSerialization(String[] patterns) throws IOException { - for (int i = 0, len = patterns.length; i < len; i++) { - NamePattern p = new NamePattern(patterns[i]); + for (String pattern : patterns) { + NamePattern p = new NamePattern(pattern); checkSerialization(p); } } diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java index d2a8fd245..f7d454f0c 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/PointcutRewriterTest.java @@ -310,8 +310,8 @@ public class PointcutRewriterTest extends TestCase { public void testKindSetOfThis() { Pointcut p = getPointcut("this(Foo)"); Set matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object o : matches) { + Shadow.Kind kind = (Shadow.Kind) o; assertFalse("No kinds that don't have a this", kind.neverHasThis()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { @@ -322,8 +322,8 @@ public class PointcutRewriterTest extends TestCase { // + @ p = getPointcut("@this(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object match : matches) { + Shadow.Kind kind = (Shadow.Kind) match; assertFalse("No kinds that don't have a this", kind.neverHasThis()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { @@ -336,8 +336,8 @@ public class PointcutRewriterTest extends TestCase { public void testKindSetOfTarget() { Pointcut p = getPointcut("target(Foo)"); Set matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object o : matches) { + Shadow.Kind kind = (Shadow.Kind) o; assertFalse("No kinds that don't have a target", kind.neverHasTarget()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { @@ -348,8 +348,8 @@ public class PointcutRewriterTest extends TestCase { // + @ p = getPointcut("@target(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object match : matches) { + Shadow.Kind kind = (Shadow.Kind) match; assertFalse("No kinds that don't have a target", kind.neverHasTarget()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { @@ -383,8 +383,8 @@ public class PointcutRewriterTest extends TestCase { public void testKindSetOfWithinCode() { Pointcut p = getPointcut("withincode(* foo(..))"); Set matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object o : matches) { + Shadow.Kind kind = (Shadow.Kind) o; assertFalse("No kinds that are themselves enclosing", (kind.isEnclosingKind() && kind != Shadow.ConstructorExecution && kind != Shadow.Initialization)); } @@ -398,8 +398,8 @@ public class PointcutRewriterTest extends TestCase { // + @ p = getPointcut("@withincode(Foo)"); matches = Shadow.toSet(p.couldMatchKinds()); - for (Iterator iter = matches.iterator(); iter.hasNext();) { - Shadow.Kind kind = (Shadow.Kind) iter.next(); + for (Object match : matches) { + Shadow.Kind kind = (Shadow.Kind) match; assertFalse("No kinds that are themselves enclosing", kind.isEnclosingKind()); } for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) { diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java index 52f82bfd7..756a53d7f 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternMatchSpeedTestCase.java @@ -93,12 +93,12 @@ public class SignaturePatternMatchSpeedTestCase extends PatternsTestCase { public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException { p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); - for (int i = 0; i < yes.length; i++) { - checkMatch(p, yes[i], true); + for (Member value : yes) { + checkMatch(p, value, true); } - for (int i = 0; i < no.length; i++) { - checkMatch(p, no[i], false); + for (Member member : no) { + checkMatch(p, member, false); } checkSerialization(p); diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java index 6c6f1f985..1920646e4 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/SignaturePatternTestCase.java @@ -144,12 +144,12 @@ public class SignaturePatternTestCase extends PatternsTestCase { public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException { p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0)); - for (int i = 0; i < yes.length; i++) { - checkMatch(p, yes[i], true); + for (Member value : yes) { + checkMatch(p, value, true); } - for (int i = 0; i < no.length; i++) { - checkMatch(p, no[i], false); + for (Member member : no) { + checkMatch(p, member, false); } checkSerialization(p); diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java index a141e2b0c..8d43fcce2 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternListTestCase.java @@ -143,8 +143,8 @@ public class TypePatternListTestCase extends PatternsTestCase { "(int, .., .., ..)", "(int, .., .., int)", "(int, .., int, ..)", "(int, .., int, int)", "(int, int, .., ..)", "(int, int, .., int)", "(int, int, int, ..)", "(int, int, int, int)" }; - for (int i = 0, len = patterns.length; i < len; i++) { - checkSerialization(patterns[i]); + for (String pattern : patterns) { + checkSerialization(pattern); } } diff --git a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java index 058bd2450..5ec92e1ec 100644 --- a/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java +++ b/org.aspectj.matcher/src/test/java/org/aspectj/weaver/patterns/TypePatternTestCase.java @@ -235,8 +235,8 @@ public class TypePatternTestCase extends PatternsTestCase { String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*", "java..util..*", "*.*.Object", "*", }; - for (int i = 0, len = patterns.length; i < len; i++) { - checkSerialization(patterns[i]); + for (String pattern : patterns) { + checkSerialization(pattern); } } diff --git a/runtime/src/main/java/org/aspectj/internal/lang/reflect/StringToType.java b/runtime/src/main/java/org/aspectj/internal/lang/reflect/StringToType.java index 4be9fd71e..c658bbbd0 100644 --- a/runtime/src/main/java/org/aspectj/internal/lang/reflect/StringToType.java +++ b/runtime/src/main/java/org/aspectj/internal/lang/reflect/StringToType.java @@ -48,9 +48,9 @@ public class StringToType { } catch (ClassNotFoundException e) { // could be a type variable TypeVariable[] tVars = classScope.getTypeParameters(); - for (int i = 0; i < tVars.length; i++) { - if (tVars[i].getName().equals(typeName)) { - return tVars[i]; + for (TypeVariable tVar : tVars) { + if (tVar.getName().equals(typeName)) { + return tVar; } } throw new ClassNotFoundException(typeName); diff --git a/runtime/src/main/java/org/aspectj/runtime/internal/cflowstack/ThreadCounterImpl11.java b/runtime/src/main/java/org/aspectj/runtime/internal/cflowstack/ThreadCounterImpl11.java index 71aaacd62..bc53f9317 100644 --- a/runtime/src/main/java/org/aspectj/runtime/internal/cflowstack/ThreadCounterImpl11.java +++ b/runtime/src/main/java/org/aspectj/runtime/internal/cflowstack/ThreadCounterImpl11.java @@ -49,8 +49,8 @@ public class ThreadCounterImpl11 implements ThreadCounter { Thread t = (Thread)e.nextElement(); if (!t.isAlive()) dead_stacks.add(t); } - for (Iterator e = dead_stacks.iterator(); e.hasNext(); ) { - Thread t = (Thread)e.next(); + for (Object dead_stack : dead_stacks) { + Thread t = (Thread) dead_stack; counters.remove(t); } change_count = 0; diff --git a/runtime/src/main/java/org/aspectj/runtime/reflect/MethodSignatureImpl.java b/runtime/src/main/java/org/aspectj/runtime/reflect/MethodSignatureImpl.java index 17416bada..76ea6c6cf 100644 --- a/runtime/src/main/java/org/aspectj/runtime/reflect/MethodSignatureImpl.java +++ b/runtime/src/main/java/org/aspectj/runtime/reflect/MethodSignatureImpl.java @@ -102,8 +102,8 @@ class MethodSignatureImpl extends CodeSignatureImpl implements MethodSignature { } Class[] superinterfaces = type.getInterfaces(); if (superinterfaces != null) { - for (int i = 0; i < superinterfaces.length; i++) { - m = search(superinterfaces[i], name, params, searched); + for (Class superinterface : superinterfaces) { + m = search(superinterface, name, params, searched); if (m != null) { return m; } diff --git a/runtime/src/test/java/org/aspectj/internal/lang/reflect/AjTypeWithAspectsTest.java b/runtime/src/test/java/org/aspectj/internal/lang/reflect/AjTypeWithAspectsTest.java index af72d26f5..a2f33f91b 100644 --- a/runtime/src/test/java/org/aspectj/internal/lang/reflect/AjTypeWithAspectsTest.java +++ b/runtime/src/test/java/org/aspectj/internal/lang/reflect/AjTypeWithAspectsTest.java @@ -146,9 +146,9 @@ public class AjTypeWithAspectsTest extends TestCase { assertEquals(10,ms.length); //AV was corrupted, cannot rely on ordering String match = ""; - for (int i = 0; i < ms.length; i++) { - match = match + "--" + ms[i].getName(); - } + for (Method m : ms) { + match = match + "--" + m.getName(); + } assertTrue(match.indexOf("aMethod") >=0); } diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc10.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc10.java index 065f44e71..354702f5a 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc10.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc10.java @@ -439,32 +439,32 @@ public class Ajc10 extends MatchingTask { int numargfiles = 0; if (argfiles != null) { - for (Iterator i = argfiles.iterator(); i.hasNext();) { - String name = i.next()+""; - File argfile = project.resolveFile(name); - if (check(argfile, name, false, location)) { - cmd.createArgument().setValue("-argfile"); - cmd.createArgument().setFile(argfile); - numargfiles++; - } - } + for (Object o : argfiles) { + String name = o + ""; + File argfile = project.resolveFile(name); + if (check(argfile, name, false, location)) { + cmd.createArgument().setValue("-argfile"); + cmd.createArgument().setFile(argfile); + numargfiles++; + } + } } int numfiles = 0; if (srcdir != null) { // todo: ignore any srcdir if any argfiles and no explicit includes String[] dirs = srcdir.list(); - for (int i = 0; i < dirs.length; i++) { - File dir = project.resolveFile(dirs[i]); - check(dir, dirs[i], true, location); - String[] files = getDirectoryScanner(dir).getIncludedFiles(); - for (int j = 0; j < files.length; j++) { - File file = new File(dir, files[j]); - if (FileUtil.hasSourceSuffix(file)) { - cmd.createArgument().setFile(file); - numfiles++; - } - } - } + for (String value : dirs) { + File dir = project.resolveFile(value); + check(dir, value, true, location); + String[] files = getDirectoryScanner(dir).getIncludedFiles(); + for (String s : files) { + File file = new File(dir, s); + if (FileUtil.hasSourceSuffix(file)) { + cmd.createArgument().setFile(file); + numfiles++; + } + } + } } if ((null != ignoredOptions) && (ignoredOptions.size() > 0)) { log("The following attributes were ignored " + ignoredOptions, @@ -568,10 +568,10 @@ public class Ajc10 extends MatchingTask { public static String render(String[] args) { if (null == args) return ""; StringBuffer sb = new StringBuffer(); - for (int i = 0; i < args.length; i++) { - sb.append(args[i]); - sb.append(" "); - } + for (String arg : args) { + sb.append(arg); + sb.append(" "); + } return sb.toString(); } diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc2.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc2.java index f31c7558f..a089f00b9 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc2.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajc2.java @@ -434,14 +434,14 @@ public class Ajc2 extends Javac { // Otherwise we want to add all .java files to the compileList else { - for (int i = 0; i < files.length; i++) { - File newFile = new File(srcDir, files[i]); - if (newFile != null && - newFile.exists() && - newFile.getName().endsWith(".java")) { - newFiles.add(newFile); - } - } + for (String file : files) { + File newFile = new File(srcDir, file); + if (newFile != null && + newFile.exists() && + newFile.getName().endsWith(".java")) { + newFiles.add(newFile); + } + } } // Add the new included files diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcCompilerAdapter.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcCompilerAdapter.java index 1542f6cb4..a0c84d2db 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcCompilerAdapter.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcCompilerAdapter.java @@ -94,9 +94,9 @@ public class AjcCompilerAdapter implements CompilerAdapter { tempAjc.setIncludeantruntime(javac.getIncludeantruntime()); // XXX unsupported File[] files = javac.getFileList(); if (null != files) { - for (int i = 0; i < files.length; i++) { - tempAjc.backdoorSetFile(files[i]); - } + for (File file : files) { + tempAjc.backdoorSetFile(file); + } } ajc = tempAjc; } diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcTask.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcTask.java index 4f40526c7..c68a1eb59 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcTask.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/AjcTask.java @@ -1161,9 +1161,9 @@ public class AjcTask extends MatchingTask { String[] makeCommand() { ArrayList result = new ArrayList(); if (0 < ignored.size()) { - for (Iterator iter = ignored.iterator(); iter.hasNext();) { - logVerbose("ignored: " + iter.next()); - } + for (Object o : ignored) { + logVerbose("ignored: " + o); + } } // when copying resources, use temp jar for class output // then copy temp jar contents and resources to output jar @@ -1576,14 +1576,15 @@ public class AjcTask extends MatchingTask { } } if (0 < adapterFiles.size()) { - for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - if (file.canRead() && FileUtil.hasSourceSuffix(file)) { - list.add(file.getAbsolutePath()); - } else { - this.logger.warning("skipping file: " + file); - } - } + for (Object adapterFile : adapterFiles) { + File file = (File) adapterFile; + if (file.canRead() && FileUtil.hasSourceSuffix(file)) { + list.add(file.getAbsolutePath()); + } + else { + this.logger.warning("skipping file: " + file); + } + } } } diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajdoc.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajdoc.java index b787a2f89..194efaf22 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajdoc.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/Ajdoc.java @@ -178,9 +178,9 @@ public class Ajdoc extends MatchingTask { File baseDir = fs.getDir(getProject()); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] files = ds.getIncludedFiles(); - for (int i = 0; i < files.length; i++) { - sourcefiles.add((new File(baseDir, files[i])).getAbsolutePath()); - } + for (String file : files) { + sourcefiles.add((new File(baseDir, file)).getAbsolutePath()); + } } } @@ -606,17 +606,16 @@ public class Ajdoc extends MatchingTask { cmd.createArgument().setValue("-docletpath"); cmd.createArgument().setPath(doclet.path); } - for (Iterator i = doclet.params.iterator(); i.hasNext();) { - Param param = (Param)i.next(); - if (param.name == null) { - throw new BuildException("Doclet params cannot be null!", - getLocation()); - } - cmd.createArgument().setValue(param.name); - if (param.value == null) { - cmd.createArgument().setValue(param.value); - } - } + for (Param param : doclet.params) { + if (param.name == null) { + throw new BuildException("Doclet params cannot be null!", + getLocation()); + } + cmd.createArgument().setValue(param.name); + if (param.value == null) { + cmd.createArgument().setValue(param.value); + } + } } Map<String,List<String>> groupMap = new HashMap<String,List<String>>(); for (Group group: groups) { @@ -647,48 +646,48 @@ public class Ajdoc extends MatchingTask { cmd.createArgument().setValue(pkgstr); } if (argfiles != null) { - for (Iterator i = argfiles.iterator(); i.hasNext();) { - String name = i.next()+""; - File argfile = getProject().resolveFile(name); - if (check(argfile, name, false, getLocation())) { - cmd.createArgument().setValue("-argfile"); - cmd.createArgument().setFile(argfile); - } - } + for (File file : argfiles) { + String name = file + ""; + File argfile = getProject().resolveFile(name); + if (check(argfile, name, false, getLocation())) { + cmd.createArgument().setValue("-argfile"); + cmd.createArgument().setFile(argfile); + } + } } if (packageList != null) { cmd.createArgument().setValue("@" + packageList); } if (null != packagenames) { - for (Iterator<String> i = packagenames.iterator(); i.hasNext();) { - cmd.createArgument().setValue((String)i.next()); - } + for (String packagename : packagenames) { + cmd.createArgument().setValue(packagename); + } } // support for include parameter as a MatchingTask int numfiles = 0; if (sourcepath != null) { String[] dirs = sourcepath.list(); - for (int i = 0; i < dirs.length; i++) { - File dir = getProject().resolveFile(dirs[i]); - check(dir, dirs[i], true, getLocation()); - String[] files = getDirectoryScanner(dir).getIncludedFiles(); - for (int j = 0; j < files.length; j++) { - File file = new File(dir, files[j]); - if (file.getName().endsWith(".java") - || file.getName().endsWith(".aj")) { - cmd.createArgument().setFile(file); - numfiles++; - } - } - } + for (String value : dirs) { + File dir = getProject().resolveFile(value); + check(dir, value, true, getLocation()); + String[] files = getDirectoryScanner(dir).getIncludedFiles(); + for (String s : files) { + File file = new File(dir, s); + if (file.getName().endsWith(".java") + || file.getName().endsWith(".aj")) { + cmd.createArgument().setFile(file); + numfiles++; + } + } + } } addFileSets(); if (sourcefiles != null) { - for (Iterator<String> i = sourcefiles.iterator(); i.hasNext();) { - // let ajdoc resolve sourcefiles relative to sourcepath, - cmd.createArgument().setValue(i.next()); - } + for (String sourcefile : sourcefiles) { + // let ajdoc resolve sourcefiles relative to sourcepath, + cmd.createArgument().setValue(sourcefile); + } } // XXX PR682 weak way to report errors - need to refactor int result = compile(); diff --git a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/compilers/Ajc.java b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/compilers/Ajc.java index 690cccf22..0242b4d58 100644 --- a/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/compilers/Ajc.java +++ b/taskdefs/src/main/java/org/aspectj/tools/ant/taskdefs/compilers/Ajc.java @@ -198,25 +198,23 @@ public class Ajc extends DefaultCompilerAdapter { niceSourceList.append(" to be compiled:"); niceSourceList.append(lSep); - for (int i=0; i < compileList.length; i++) { - - // DefaultCompilerAdapter only expects .java files but we must deal - // with .lst files also - File file = compileList[i]; - - if (file == null) continue; - - String arg = file.getAbsolutePath(); - String rest = ""; - String name = file.getName(); - - // For .java files take the default behavior and add that - // file to the command line - if (name.endsWith(".java")) { - cmd.createArgument().setValue(arg); - } - niceSourceList.append(" " + arg + rest + lSep); - } + for (File file : compileList) { + + // DefaultCompilerAdapter only expects .java files but we must deal + // with .lst files also + if (file == null) continue; + + String arg = file.getAbsolutePath(); + String rest = ""; + String name = file.getName(); + + // For .java files take the default behavior and add that + // file to the command line + if (name.endsWith(".java")) { + cmd.createArgument().setValue(arg); + } + niceSourceList.append(" " + arg + rest + lSep); + } attributes.log(niceSourceList.toString(), Project.MSG_VERBOSE); } } diff --git a/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/Ajc11CompilerAdapterTest.java b/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/Ajc11CompilerAdapterTest.java index 3b95693e2..80e9ed4a0 100644 --- a/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/Ajc11CompilerAdapterTest.java +++ b/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/Ajc11CompilerAdapterTest.java @@ -35,11 +35,11 @@ public class Ajc11CompilerAdapterTest extends TestCase { } public void tearDown() { - for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); - FileUtil.deleteContents(file); - file.delete(); - } + for (Object tempFile : tempFiles) { + File file = (File) tempFile; + FileUtil.deleteContents(file); + file.delete(); + } } // public void testCompilerAdapterWithJavac() { // XXX requires tools.jar diff --git a/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java b/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java index c149ad79b..b1f7c7b4f 100644 --- a/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java +++ b/taskdefs/src/test/java/org/aspectj/tools/ant/taskdefs/AjcTaskTest.java @@ -187,17 +187,17 @@ public class AjcTaskTest extends TestCase { } private void checkContains(String[] cmd, String option, boolean contains) { - for (int i = 0; i < cmd.length; i++) { - if (option.equals(cmd[i])) { - if (contains) { - return; - } else { - assertTrue( - "not expecting " + option + " in " + Arrays.asList(cmd), - false); - } - } - } + for (String s : cmd) { + if (option.equals(s)) { + if (contains) { + return; + } else { + assertTrue( + "not expecting " + option + " in " + Arrays.asList(cmd), + false); + } + } + } if (contains) { assertTrue( "expecting " + option + " in " + Arrays.asList(cmd), @@ -279,8 +279,8 @@ public class AjcTaskTest extends TestCase { AjcTask task = getTask(NOFILE, null); String[] cmd = task.makeCommand(); - for (int i = 0; i < cmd.length; i++) { - assertTrue(!"-d".equals(cmd[i])); + for (String s : cmd) { + assertTrue(!"-d".equals(s)); } } @@ -398,14 +398,14 @@ public class AjcTaskTest extends TestCase { String[] expected = {"copyMe.htm", "pack/includeme", "pack/Pack.class", "Default.class"}; String[] unexpected = {"doNotCopy", "skipTxtFiles.txt", "pack/something.txt"}; - for (int i = 0; i < expected.length; i++) { - JarEntry entry = jarFile.getJarEntry(expected[i]); - assertTrue(expected[i] + " not found", null != entry); - } - for (int i = 0; i < unexpected.length; i++) { - JarEntry entry = jarFile.getJarEntry(unexpected[i]); - assertTrue(unexpected[i] + " found", null == entry); - } + for (String value : expected) { + JarEntry entry = jarFile.getJarEntry(value); + assertTrue(value + " not found", null != entry); + } + for (String s : unexpected) { + JarEntry entry = jarFile.getJarEntry(s); + assertTrue(s + " found", null == entry); + } } public void testInpathDirCopyFilterError() { @@ -656,30 +656,30 @@ public class AjcTaskTest extends TestCase { public void testVersions() { String[] inputs = AjcTask.TARGET_INPUTS; - for (int i = 0; i < inputs.length; i++) { + for (String value : inputs) { AjcTask task = getTask(NOFILE); - task.setTarget(inputs[i]); + task.setTarget(value); String[] cmd = task.makeCommand(); - checkContains(cmd, "-target", true); - checkContains(cmd, inputs[i], true); + checkContains(cmd, "-target", true); + checkContains(cmd, value, true); } inputs = AjcTask.SOURCE_INPUTS; - for (int i = 0; i < inputs.length; i++) { - AjcTask task = getTask(NOFILE); - task.setSource(inputs[i]); - String[] cmd = task.makeCommand(); - checkContains(cmd, "-source", true); - checkContains(cmd, inputs[i], true); - } + for (String s : inputs) { + AjcTask task = getTask(NOFILE); + task.setSource(s); + String[] cmd = task.makeCommand(); + checkContains(cmd, "-source", true); + checkContains(cmd, s, true); + } inputs = AjcTask.COMPLIANCE_INPUTS; - for (int i = 0; i < inputs.length; i++) { - AjcTask task = getTask(NOFILE); - task.setCompliance(inputs[i]); - String[] cmd = task.makeCommand(); - checkContains(cmd, inputs[i], true); - } + for (String input : inputs) { + AjcTask task = getTask(NOFILE); + task.setCompliance(input); + String[] cmd = task.makeCommand(); + checkContains(cmd, input, true); + } } public void testClasspath() { @@ -807,11 +807,11 @@ public class AjcTaskTest extends TestCase { "reweavable:compress", "noInline" }; - for (int i = 0; i < xopts.length; i++) { + for (String xopt : xopts) { AjcTask task = getTask(NOFILE); - task.setX(xopts[i]); + task.setX(xopt); String[] cmd = task.makeCommand(); - checkContains(cmd,"-X" + xopts[i],true); + checkContains(cmd, "-X" + xopt, true); } } @@ -1080,8 +1080,8 @@ class VerboseCommandEditor implements ICommandEditor { public static final String VERBOSE = "-verbose"; @Override public String[] editCommand(String[] command) { - for (int i = 0; i < command.length; i++) { - if (VERBOSE.equals(command[i])) { + for (String s : command) { + if (VERBOSE.equals(s)) { return command; } } diff --git a/testing-client/src/main/java/org/aspectj/testing/Tester.java b/testing-client/src/main/java/org/aspectj/testing/Tester.java index ed0c60f3a..d42bcd994 100644 --- a/testing-client/src/main/java/org/aspectj/testing/Tester.java +++ b/testing-client/src/main/java/org/aspectj/testing/Tester.java @@ -831,10 +831,10 @@ public class Tester { /** add expected events */ public static void expectEvents(Object[] events) { if (null != events) { - for (int i = 0; i < events.length; i++) { - if (null != events[i]) { - expectEvent(events[i].toString()); - } + for (Object event : events) { + if (null != event) { + expectEvent(event.toString()); + } } } } @@ -842,11 +842,11 @@ public class Tester { /** add expected events */ public static void expectEvents(String[] events) { if (null != events) { - for (int i = 0; i < events.length; i++) { - if (null != events[i]) { - expectEvent(events[i].toString()); - } - } + for (String event : events) { + if (null != event) { + expectEvent(event.toString()); + } + } } } @@ -946,9 +946,9 @@ public class Tester { /** XXX deprecated */ public static void printEvents() { // XXX no clients? - for (Iterator<String> i = actualEvents.iterator(); i.hasNext(); ) { - System.out.println(i.next()); // XXX System.out - } + for (String actualEvent : actualEvents) { + System.out.println(actualEvent); // XXX System.out + } } /** diff --git a/testing-drivers/src/test/java/org/aspectj/testing/drivers/Harness.java b/testing-drivers/src/test/java/org/aspectj/testing/drivers/Harness.java index f1c8b3635..e932a027d 100644 --- a/testing-drivers/src/test/java/org/aspectj/testing/drivers/Harness.java +++ b/testing-drivers/src/test/java/org/aspectj/testing/drivers/Harness.java @@ -323,10 +323,10 @@ public class Harness { */ private void doEndSuite(File suiteFile, long elapsed) { Collection c = features.values(); - for (Iterator iter = c.iterator(); iter.hasNext();) { - Feature element = (Feature) iter.next(); + for (Object o : c) { + Feature element = (Feature) o; if (element.listener instanceof TestCompleteListener) { - ((TestCompleteListener)element.listener).doEndSuite(suiteFile,elapsed); + ((TestCompleteListener) element.listener).doEndSuite(suiteFile, elapsed); } } } diff --git a/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessJUnitUtil.java b/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessJUnitUtil.java index d3e05f84c..b26b5286f 100644 --- a/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessJUnitUtil.java +++ b/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessJUnitUtil.java @@ -50,12 +50,12 @@ public class HarnessJUnitUtil { if (HarnessJUnitUtil.isEmpty(options)) { options = new String[][] {new String[0]}; } - for (int i = 0; i < suites.length; i++) { - for (int j = 0; j < options.length; j++) { - Test t = AjctestsAdapter.make(suites[i], options[j]); - suite.addTest(t); - } - } + for (String s : suites) { + for (String[] option : options) { + Test t = AjctestsAdapter.make(s, option); + suite.addTest(t); + } + } } return suite; } diff --git a/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessSelectionTest.java b/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessSelectionTest.java index ac937ac44..a292962fc 100644 --- a/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessSelectionTest.java +++ b/testing-drivers/src/test/java/org/aspectj/testing/drivers/HarnessSelectionTest.java @@ -87,9 +87,9 @@ public class HarnessSelectionTest extends TestCase { String[] files = new String[] { SELECT, INCREMENTAL, TITLE_LIST_ONE, TITLE_LIST_PLURAL }; - for (int i = 0; i < files.length; i++) { - assertTrue(files[i], new File(files[i]).canRead()); - } + for (String file : files) { + assertTrue(file, new File(file).canRead()); + } } public void testIncrementalSuite() { @@ -358,10 +358,10 @@ public class HarnessSelectionTest extends TestCase { assertTrue(children.length + "!= expRun=" + exp.testsRun, exp.testsRun == children.length); int actPass = 0; - for (int i = 0; i < children.length; i++) { - if (RunValidator.NORMAL.runPassed(children[i])) { - actPass++; - } + for (IRunStatus child : children) { + if (RunValidator.NORMAL.runPassed(child)) { + actPass++; + } } if (exp.passed != actPass) { assertTrue("exp.passed=" + exp.passed + " != actPass=" + actPass, false); diff --git a/testing-util/src/main/java/org/aspectj/testing/util/TestUtil.java b/testing-util/src/main/java/org/aspectj/testing/util/TestUtil.java index ef6109e37..6be6cc61e 100644 --- a/testing-util/src/main/java/org/aspectj/testing/util/TestUtil.java +++ b/testing-util/src/main/java/org/aspectj/testing/util/TestUtil.java @@ -126,8 +126,8 @@ public final class TestUtil { // TODO support others loaded dynamically Map<String,Object> map = new HashMap<>(); - for (Iterator<Object> iter = LIB_RPATHS.keySet().iterator(); iter.hasNext();) { - String key = (String) iter.next(); + for (Object o : LIB_RPATHS.keySet()) { + String key = (String) o; String path = LIB_RPATHS.getProperty(key); File file = null; URL url = null; @@ -206,14 +206,14 @@ public final class TestUtil { } StringBuffer path = new StringBuffer(); boolean started = false; - for (int i = 0; i < entries.length; i++) { - if (null != entries[i]) { + for (Object entry : entries) { + if (null != entry) { if (started) { path.append(File.pathSeparator); } else { started = true; } - path.append(entries[i].toString()); + path.append(entry.toString()); } } return path.toString(); @@ -476,11 +476,11 @@ public final class TestUtil { } String[] paths = FileUtil.listFiles(expectedBaseDir); boolean result = true; - for (int i = 0; i < paths.length; i++) { - if (-1 != paths[i].indexOf("CVS")) { + for (String path : paths) { + if (-1 != path.indexOf("CVS")) { continue; } - if (!sameFiles(handler, expectedBaseDir, actualBaseDir, paths[i]) && result) { + if (!sameFiles(handler, expectedBaseDir, actualBaseDir, path) && result) { result = false; if (fastFail) { break; diff --git a/testing-util/src/test/java/org/aspectj/testingutil/TestUtilTest.java b/testing-util/src/test/java/org/aspectj/testingutil/TestUtilTest.java index 3a514a0ed..0807bd2a3 100644 --- a/testing-util/src/test/java/org/aspectj/testingutil/TestUtilTest.java +++ b/testing-util/src/test/java/org/aspectj/testingutil/TestUtilTest.java @@ -96,15 +96,15 @@ public class TestUtilTest extends TestCase { public void testParseBoolean() { { String[] trues = {"true", "TRUE", "on", "ON" }; - for (int i = 0; i < trues.length; i++) { - assertTrue(trues[i], TestUtil.parseBoolean(trues[i])); - } + for (String aTrue : trues) { + assertTrue(aTrue, TestUtil.parseBoolean(aTrue)); + } } { String[] falses = {"false", "FALSE", "off", "off" }; - for (int i = 0; i < falses.length; i++) { - assertTrue(falses[i], !TestUtil.parseBoolean(falses[i])); - } + for (String fals : falses) { + assertTrue(fals, !TestUtil.parseBoolean(fals)); + } } String[] errors = {"fals", "tru", "T", "on of" }; boolean fail = false; diff --git a/testing/src/test/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java b/testing/src/test/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java index 0dcc23dfd..67e73ed6c 100644 --- a/testing/src/test/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java +++ b/testing/src/test/java/org/aspectj/internal/tools/ant/taskdefs/Ajctest.java @@ -419,27 +419,27 @@ public class Ajctest extends Task implements PropertyChangeListener { String str = ""; if (files.size() > 0) { str += "files:" + "\n"; - for (Iterator<File> i = files.iterator(); i.hasNext();) { - str += "\t" + i.next() + "\n"; - } + for (File file : files) { + str += "\t" + file + "\n"; + } } if (argfiles.size() > 0) { str += "argfiles:" + "\n"; - for (Iterator<File> i = argfiles.iterator(); i.hasNext();) { - str += "\t" + i.next() + "\n"; - } + for (File argfile : argfiles) { + str += "\t" + argfile + "\n"; + } } if (args.size() > 0) { str += "args:" + "\n"; - for (Iterator i = args.iterator(); i.hasNext();) { - str += "\t" + i.next() + "\n"; - } + for (Argument arg : args) { + str += "\t" + arg + "\n"; + } } if (testclasses.size() > 0) { str += "classes:" + "\n"; - for (Iterator i = testclasses.iterator(); i.hasNext();) { - str += "\t" + i.next() + "\n"; - } + for (Run testclass : testclasses) { + str += "\t" + testclass + "\n"; + } } return str; } @@ -581,26 +581,24 @@ public class Ajctest extends Task implements PropertyChangeListener { File src = getDir(project); argfiles = new Vector<>(); files = new Vector<>(); - for(Iterator<Argfile> iter = argfileNames.iterator(); iter.hasNext();) { - String name = iter.next().name; - File argfile = new File(src, name); - if (check(argfile, name, location)) argfiles.add(argfile); - } + for (Argfile argfileName : argfileNames) { + String name = argfileName.name; + File argfile = new File(src, name); + if (check(argfile, name, location)) argfiles.add(argfile); + } if (havecludes || argfiles.size() <= 0) { String[] filenames = getDirectoryScanner(project).getIncludedFiles(); - for (int j = 0; j < filenames.length; j++) { - String name = filenames[j]; - if (name.endsWith(".java")) { - File file = new File(src, name); - if (check(file, name, location)) files.add(file); - } - } - } - for (Iterator i = Ajctest.this.testclasses.iterator(); - i.hasNext();) { - this.testclasses.add((Run)i.next()); - } + for (String name : filenames) { + if (name.endsWith(".java")) { + File file = new File(src, name); + if (check(file, name, location)) files.add(file); + } + } + } + for (Run run : Ajctest.this.testclasses) { + this.testclasses.add(run); + } if (this.classpath == null) { setClasspath(Ajctest.this.classpath); } @@ -611,9 +609,9 @@ public class Ajctest extends Task implements PropertyChangeListener { this.ajdoc = Ajctest.this.ajdoc; } if (this.fork) { - for (Iterator<Run> i = this.testclasses.iterator(); i.hasNext();) { - i.next().setFork(fork); - } + for (Run testclass : this.testclasses) { + testclass.setFork(fork); + } } if (!this.noclean) { this.noclean = Ajctest.this.noclean; @@ -691,35 +689,35 @@ public class Ajctest extends Task implements PropertyChangeListener { private void log(String space, List<?> list, String title) { if (list == null || list.size() < 1) return; log(space + title); - for (Iterator<?> i = list.iterator(); i.hasNext();) { - log(space + " " + i.next()); - } + for (Object o : list) { + log(space + " " + o); + } } private void execute(Testset testset, List<Arg> args) throws BuildException { if (testset.files.size() > 0) { log("\tfiles:"); - for (Iterator<File> i = testset.files.iterator(); i.hasNext();) { - log("\t " + i.next()); - } + for (File file : testset.files) { + log("\t " + file); + } } if (testset.argfiles.size() > 0) { log("\targfiles:"); - for (Iterator<File> i = testset.argfiles.iterator(); i.hasNext();) { - log("\t " + i.next()); - } + for (File file : testset.argfiles) { + log("\t " + file); + } } if (args.size() > 0) { log("\targs:"); - for (Iterator<Arg> i = args.iterator(); i.hasNext();) { - log("\t " + i.next()); - } + for (Arg arg : args) { + log("\t " + arg); + } } if (testset.testclasses.size() > 0) { log("\tclasses:"); - for (Iterator<Run> i = testset.testclasses.iterator(); i.hasNext();) { - log("\t " + i.next()); - } + for (Run testclass : testset.testclasses) { + log("\t " + testclass); + } } if (!testset.noclean && (!isSet("noclean") && !isSet("nocompile"))) { @@ -728,11 +726,11 @@ public class Ajctest extends Task implements PropertyChangeListener { } delete(workingdir); make(workingdir); - for (Iterator<String> i = testset.depends.iterator(); i.hasNext();) { - String target = i.next()+""; - // todo: capture failures here? - project.executeTarget(target); - } + for (String depend : testset.depends) { + String target = depend + ""; + // todo: capture failures here? + project.executeTarget(target); + } int exit; if (!isSet("nodoc") && testset.ajdoc != null) { log("\tdoc... " + testset.ajdoc); @@ -785,19 +783,18 @@ public class Ajctest extends Task implements PropertyChangeListener { -1, "run"); } else if (!isSet("norun")) { - for (Iterator<Run> i = testset.testclasses.iterator(); i.hasNext();) { - Run testclass = i.next(); - log("\ttest..." + testclass.classname()); - if (null != destdir) { - testclass.setClassesDir(destdir.getAbsolutePath()); - } - if ((exit = testclass.executeJava()) != 0) { - post(testset, new Vector(), testclass.msgs, exit, "run"); - } else { - fire("run.good"); - } - fire("run.done"); - } + for (Run testclass : testset.testclasses) { + log("\ttest..." + testclass.classname()); + if (null != destdir) { + testclass.setClassesDir(destdir.getAbsolutePath()); + } + if ((exit = testclass.executeJava()) != 0) { + post(testset, new Vector(), testclass.msgs, exit, "run"); + } else { + fire("run.good"); + } + fire("run.done"); + } } log(""); } @@ -1288,23 +1285,21 @@ public class Ajctest extends Task implements PropertyChangeListener { private List<List<Arg>> argcombo(List<Argument> arguments) { List<Argument> combos = new Vector<>(); List<Arg> always = new Vector<>(); - for (Iterator<Argument> iter = arguments.iterator(); iter.hasNext();) { - Argument arg = iter.next(); - if (arg.values.size() == 0) arg.values.add(""); - if (!arg.always && !arg.values.contains(null)) arg.values.add(null); - if (arg.values.size() > 0) { - combos.add(arg); - } else if (arg.always) { - always.add(new Arg(arg.name, arg.values.get(0)+"", arg.isj)); - } - } + for (Argument arg : arguments) { + if (arg.values.size() == 0) arg.values.add(""); + if (!arg.always && !arg.values.contains(null)) arg.values.add(null); + if (arg.values.size() > 0) { + combos.add(arg); + } else if (arg.always) { + always.add(new Arg(arg.name, arg.values.get(0) + "", arg.isj)); + } + } List<List<Arg>> argcombo = combinations(combos); - for (Iterator<Arg> iter = always.iterator(); iter.hasNext();) { - Arg arg = iter.next(); - for (Iterator<List<Arg>> comboiter = argcombo.iterator(); comboiter.hasNext();) { - comboiter.next().add(arg); - } - } + for (Arg arg : always) { + for (List<Arg> argList : argcombo) { + argList.add(arg); + } + } return argcombo; } @@ -1431,9 +1426,9 @@ public class Ajctest extends Task implements PropertyChangeListener { public AjdocWrapper(Testset testset, List args) { super(testset, ajdocArgs(args), true); String[] cmds = testset.getAjdoc().getCommandline().getCommandline(); - for (int i = 0; i < cmds.length; i++) { - this.args.add(cmds[i]); - } + for (String cmd : cmds) { + this.args.add(cmd); + } } String getMainClassName() { return "org.aspectj.tools.ajdoc.Main"; @@ -1485,34 +1480,34 @@ public class Ajctest extends Task implements PropertyChangeListener { cp.append(Path.systemClasspath); } cmd.createArgument().setPath(cp); - for (Iterator iter = args.iterator(); iter.hasNext();) { - Arg arg = (Arg)iter.next(); - if (arg.isj) { - cmd.createArgument().setValue(arg.name); - if (!arg.value.equals("")) { - cmd.createArgument().setValue(arg.value); - } - } - } + for (Object item : args) { + Arg arg = (Arg) item; + if (arg.isj) { + cmd.createArgument().setValue(arg.name); + if (!arg.value.equals("")) { + cmd.createArgument().setValue(arg.value); + } + } + } cmd.createArgument().setValue(getMainClassName()); boolean alreadySetDestDir = false; boolean alreadySetClasspath = false; - for (Iterator iter = args.iterator(); iter.hasNext();) { - Arg arg = (Arg)iter.next(); - if (!arg.isj) { - cmd.createArgument().setValue(arg.name); - if (arg.name.equals("-d")) { - setDestdir(arg.value+""); - alreadySetDestDir = true; - } - if (arg.name.equals("-classpath")) { - alreadySetClasspath = true; - } - if (!arg.value.equals("")) { - cmd.createArgument().setValue(arg.value); - } - } - } + for (Object o : args) { + Arg arg = (Arg) o; + if (!arg.isj) { + cmd.createArgument().setValue(arg.name); + if (arg.name.equals("-d")) { + setDestdir(arg.value + ""); + alreadySetDestDir = true; + } + if (arg.name.equals("-classpath")) { + alreadySetClasspath = true; + } + if (!arg.value.equals("")) { + cmd.createArgument().setValue(arg.value); + } + } + } if (destdir == null) { setDestdir("."); } @@ -1530,13 +1525,13 @@ public class Ajctest extends Task implements PropertyChangeListener { cmd.createArgument().setValue("-classpath"); cmd.createArgument().setPath(_cp); } - for (Iterator iter = testset.files.iterator(); iter.hasNext();) { - cmd.createArgument().setFile((File)iter.next()); - } - for (Iterator iter = testset.argfiles.iterator(); iter.hasNext();) { - cmd.createArgument().setValue("-argfile"); - cmd.createArgument().setFile((File)iter.next()); - } + for (File value : testset.files) { + cmd.createArgument().setFile(value); + } + for (File file : testset.argfiles) { + cmd.createArgument().setValue("-argfile"); + cmd.createArgument().setFile(file); + } return cmd; } } @@ -1622,19 +1617,18 @@ public class Ajctest extends Task implements PropertyChangeListener { private List<List<Arg>> combinations(List<Argument> arglist) { List<List<Arg>> result = new Vector<>(); result.add(new Vector<Arg>()); - for (Iterator<Argument> iter = arglist.iterator(); iter.hasNext();) { - Argument arg = iter.next(); - int N = result.size(); - for (int i = 0; i < N; i++) { - List<Arg> to = result.remove(0); - for (Iterator<String> valiter = arg.values.iterator(); valiter.hasNext();) { - List<Arg> newlist = new Vector<>(to); - Object val = valiter.next(); - if (val != null) newlist.add(new Arg(arg.name, val+"", arg.isj)); - result.add(newlist); - } - } - } + for (Argument arg : arglist) { + int N = result.size(); + for (int i = 0; i < N; i++) { + List<Arg> to = result.remove(0); + for (String s : arg.values) { + List<Arg> newlist = new Vector<>(to); + Object val = s; + if (val != null) newlist.add(new Arg(arg.name, val + "", arg.isj)); + result.add(newlist); + } + } + } return result; } @@ -1764,9 +1758,9 @@ public class Ajctest extends Task implements PropertyChangeListener { Object[] names = new String[] { "Task", "Type", "Number", "Time" }; - for (int i = 0; i < names.length; i++) { - model.addColumn(names[i]); - } + for (Object name : names) { + model.addColumn(name); + } table = new TJable(model, failures); this.add(new JScrollPane(table), BorderLayout.CENTER); } @@ -1841,19 +1835,19 @@ public class Ajctest extends Task implements PropertyChangeListener { "Files", "Classnames", }; - for (int i = 0; i < os.length; i++) { - String name = os[i]+""; - JLabel label = new JLabel(name+":"); - JTextField comp = new JTextField(25); - comp.setEditable(false); - comp.setBackground(Color.white); - comp.setBorder(BorderFactory. - createBevelBorder(BevelBorder.LOWERED)); - label.setLabelFor(comp); - fields.put(name, comp); - add(label, gbc.forLabel()); - add(comp, gbc.forField()); - } + for (Object o : os) { + String name = o + ""; + JLabel label = new JLabel(name + ":"); + JTextField comp = new JTextField(25); + comp.setEditable(false); + comp.setBackground(Color.white); + comp.setBorder(BorderFactory. + createBevelBorder(BevelBorder.LOWERED)); + label.setLabelFor(comp); + fields.put(name, comp); + add(label, gbc.forLabel()); + add(comp, gbc.forField()); + } add(new JLabel(), gbc.forLastLabel()); } } diff --git a/testing/src/test/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java b/testing/src/test/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java index 59974f1b1..966166c33 100644 --- a/testing/src/test/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java +++ b/testing/src/test/java/org/aspectj/testing/AutowiredXMLBasedAjcTestCase.java @@ -68,22 +68,20 @@ public abstract class AutowiredXMLBasedAjcTestCase extends XMLBasedAjcTestCase { Map<String,AjcTest> ajTests = wired.getSuiteTests(); - for (Iterator<Map.Entry<String,AjcTest>> iterator = ajTests.entrySet().iterator(); iterator.hasNext();) { - final Map.Entry<String,AjcTest> entry = iterator.next(); - - suite.addTest( - new TestCase(entry.getKey().toString()) { - - protected void runTest() { - entry.getValue().runTest(wired); - } - - public String getName() { - return entry.getKey(); - } - } - ); - } + for (final Map.Entry<String, AjcTest> entry : ajTests.entrySet()) { + suite.addTest( + new TestCase(entry.getKey().toString()) { + + protected void runTest() { + entry.getValue().runTest(wired); + } + + public String getName() { + return entry.getKey(); + } + } + ); + } } catch (Throwable t) { final String message = t.toString(); suite.addTest( @@ -99,13 +97,12 @@ public abstract class AutowiredXMLBasedAjcTestCase extends XMLBasedAjcTestCase { // this simple check avoids failure when no test.. method is found. // it could be refined to lookup in the hierarchy as well, and excluding private method as JUnit does. Method[] testMethods = testCaseClass.getDeclaredMethods(); - for (int i = 0; i < testMethods.length; i++) { - Method testMethod = testMethods[i]; - if (testMethod.getName().startsWith("test")) { - suite.addTestSuite(testCaseClass); - break; - } - } + for (Method testMethod : testMethods) { + if (testMethod.getName().startsWith("test")) { + suite.addTestSuite(testCaseClass); + break; + } + } TestSetup wrapper = new TestSetup(suite) { /* (non-Javadoc) diff --git a/testing/src/test/java/org/aspectj/testing/WeaveSpec.java b/testing/src/test/java/org/aspectj/testing/WeaveSpec.java index 2793b63ac..b0907a3c1 100644 --- a/testing/src/test/java/org/aspectj/testing/WeaveSpec.java +++ b/testing/src/test/java/org/aspectj/testing/WeaveSpec.java @@ -115,13 +115,13 @@ public class WeaveSpec extends CompileSpec { private void collectClassFiles(File inDir, List<File> inList, List<File> toExclude) { File[] contents = inDir.listFiles(); - for (int i = 0; i < contents.length; i++) { - if (contents[i].getName().endsWith(".class")) { - if (!toExclude.contains(contents[i])) { - inList.add(contents[i]); + for (File content : contents) { + if (content.getName().endsWith(".class")) { + if (!toExclude.contains(content)) { + inList.add(content); } - } else if (contents[i].isDirectory()) { - collectClassFiles(contents[i],inList, toExclude); + } else if (content.isDirectory()) { + collectClassFiles(content, inList, toExclude); } } } diff --git a/testing/src/test/java/org/aspectj/testing/XMLBasedAjcTestCase.java b/testing/src/test/java/org/aspectj/testing/XMLBasedAjcTestCase.java index f8d12e80e..0c5b6ddeb 100644 --- a/testing/src/test/java/org/aspectj/testing/XMLBasedAjcTestCase.java +++ b/testing/src/test/java/org/aspectj/testing/XMLBasedAjcTestCase.java @@ -397,12 +397,11 @@ public abstract class XMLBasedAjcTestCase extends AjcTestCase { protected Method getMethodStartsWith(JavaClass jc, String prefix, int whichone) { Method[] meths = jc.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { System.out.println(method); if (method.getName().startsWith(prefix)) { whichone--; - if (whichone==0) { + if (whichone == 0) { return method; } } @@ -416,8 +415,7 @@ public abstract class XMLBasedAjcTestCase extends AjcTestCase { public List<LocalVariable> sortedLocalVariables(LocalVariableTable lvt) { List<LocalVariable> l = new ArrayList<LocalVariable>(); LocalVariable lv[] = lvt.getLocalVariableTable(); - for (int i = 0; i < lv.length; i++) { - LocalVariable lvEntry = lv[i]; + for (LocalVariable lvEntry : lv) { l.add(lvEntry); } Collections.sort(l, new MyComparator()); @@ -448,8 +446,7 @@ public abstract class XMLBasedAjcTestCase extends AjcTestCase { StringBuffer sb = new StringBuffer(); sb.append("LocalVariableTable. Entries=#" + lvt.getTableLength()).append("\n"); LocalVariable lv[] = lvt.getLocalVariableTable(); - for (int i = 0; i < lv.length; i++) { - LocalVariable lvEntry = lv[i]; + for (LocalVariable lvEntry : lv) { sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex()) .append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()).append("\n"); } @@ -493,10 +490,9 @@ public abstract class XMLBasedAjcTestCase extends AjcTestCase { protected Method getMethodFromClass(JavaClass clazz, String methodName) { Method[] meths = clazz.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (method.getName().equals(methodName)) { - return meths[i]; + return method; } } return null; diff --git a/testing/src/test/java/org/aspectj/testing/ajde/CompileCommand.java b/testing/src/test/java/org/aspectj/testing/ajde/CompileCommand.java index 86c5fbaf7..ccae0fd43 100644 --- a/testing/src/test/java/org/aspectj/testing/ajde/CompileCommand.java +++ b/testing/src/test/java/org/aspectj/testing/ajde/CompileCommand.java @@ -129,8 +129,8 @@ public class CompileCommand implements ICommand { try { out = new FileOutputStream(result); PrintStream outs = new PrintStream(out, true); - for (int i = 0; i < args.length; i++) { - outs.println(args[i]); + for (String arg : args) { + outs.println(arg); } return result; } catch (IOException e) { diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java index 9e302f41f..993d4f545 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AbstractRunSpec.java @@ -335,8 +335,7 @@ abstract public class AbstractRunSpec implements IRunSpec { public void addMessages(List messages) { if (null != messages) { - for (Iterator iter = messages.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : messages) { if (o instanceof IMessage) { addMessage((IMessage) o); } else { diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java index b2060480c..6a7932703 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcMessageHandler.java @@ -84,10 +84,8 @@ public class AjcMessageHandler extends MessageHandler { this.ignoreWarnings = ignoreWarnings; int fails = 0; int errors = 0; - for (Iterator iter = expectedMessagesAsList.iterator(); - iter.hasNext(); - ) { - IMessage m = (IMessage) iter.next(); + for (Object o : expectedMessagesAsList) { + IMessage m = (IMessage) o; IMessage.Kind kind = m.getKind(); if (IMessage.FAIL.isSameOrLessThan(kind)) { fails++; @@ -250,12 +248,10 @@ public class AjcMessageHandler extends MessageHandler { private boolean expecting(IMessage message) { boolean match = false; if (null != message) { - for (Iterator iter = expectedMessagesAsList.iterator(); - iter.hasNext(); - ) { + for (Object o : expectedMessagesAsList) { // amc - we have to compare against all messages to consume multiple // text matches on same line. Return true if any matches. - if (0 == COMP_IMessage.compare(message, iter.next())) { + if (0 == COMP_IMessage.compare(message, o)) { match = true; } } @@ -271,16 +267,16 @@ public class AjcMessageHandler extends MessageHandler { // remove all expected fail+ (COSTLY) ArrayList<IMessage> list = new ArrayList<>(); int leftToFilter = numExpectedFailed; - for (int i = 0; i < result.length; i++) { + for (IMessage iMessage : result) { if ((0 == leftToFilter) - || !IMessage.FAIL.isSameOrLessThan(result[i].getKind())) { - list.add(result[i]); + || !IMessage.FAIL.isSameOrLessThan(iMessage.getKind())) { + list.add(iMessage); } else { // see if this failure was expected - if (expectedMessagesHasMatchFor(result[i])) { + if (expectedMessagesHasMatchFor(iMessage)) { leftToFilter--; // ok, don't add } else { - list.add(result[i]); + list.add(iMessage); } } } @@ -293,10 +289,8 @@ public class AjcMessageHandler extends MessageHandler { * @return true if actual message is matched in the expected messages */ private boolean expectedMessagesHasMatchFor(IMessage actual) { - for (Iterator iter = expectedMessagesAsList.iterator(); - iter.hasNext(); - ) { - IMessage expected = (IMessage) iter.next(); + for (Object o : expectedMessagesAsList) { + IMessage expected = (IMessage) o; if (0 == COMP_IMessage.compare(expected, actual)) { return true; } @@ -316,8 +310,8 @@ public class AjcMessageHandler extends MessageHandler { private void render(// LangUtil instead? StringBuffer result, String prefix, String suffix, List items) { if ((null != items)) { - for (Iterator iter = items.iterator(); iter.hasNext();) { - result.append(prefix + iter.next() + suffix); + for (Object item : items) { + result.append(prefix + item + suffix); } } } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java index 4d1a47ceb..52a3e2266 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcSpecTest.java @@ -122,8 +122,7 @@ public class AjcSpecTest extends TestCase { StringBuffer sb = new StringBuffer(); sb.append("["); boolean first = true; - for (Iterator iter = list.iterator(); iter.hasNext();) { - Object o = iter.next(); + for (Object o : list) { if (!first) { sb.append(", "); } else { diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcTest.java index 629b0a0a3..cd07733ea 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcTest.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/AjcTest.java @@ -375,92 +375,91 @@ public class AjcTest extends RunSpecIterator { runtime.copy(parentRuntime); String[] globalOptions = runtime.extractOptions(VALID_OPTIONS, true); - for (int i = 0; i < globalOptions.length; i++) { - String option = globalOptions[i]; - if (!option.startsWith(OPTION_PREFIX)) { - throw new Error("only expecting " + OPTION_PREFIX + "..: " + option); - } - option = option.substring(OPTION_PREFIX.length()); - boolean keywordMustExist = false; - List<String> permittedTitles = null; - List<String> permittedTitleStrings = null; - String havePr = null; - if (option.startsWith(REQUIRE_KEYWORDS)) { - option = option.substring(REQUIRE_KEYWORDS.length()); - keywordMustExist = true; - } else if (option.startsWith(SKIP_KEYWORDS)) { - option = option.substring(SKIP_KEYWORDS.length()); - } else if (option.startsWith(TITLE_LIST)) { - option = option.substring(TITLE_LIST.length()); - permittedTitles = getTitles(option); - } else if (option.startsWith(TITLE_FAIL_LIST)) { - option = option.substring(TITLE_FAIL_LIST.length()); - permittedTitles = getTitles(option, true); - } else if (option.startsWith(TITLE_CONTAINS)) { - option = option.substring(TITLE_CONTAINS.length()); - permittedTitleStrings = getTitles(option); - } else if (option.startsWith(PICK_PR)) { - if (0 == bugId) { - skipMessage(handler, "bugId required, but no bugId for this test"); - return false; - } else { - havePr = "" + bugId; - } - option = option.substring(PICK_PR.length()); - } else { - throw new Error("unrecognized suffix: " + globalOptions[i] - + " (expecting: " + OPTION_PREFIX + VALID_SUFFIXES + "...)"); - } - if (null != permittedTitleStrings) { - boolean gotHit = false; - for (Iterator<String> iter = permittedTitleStrings.iterator(); - !gotHit && iter.hasNext(); - ) { - String substring = (String) iter.next(); - if (-1 != this.description.indexOf(substring)) { - gotHit = true; - } - } - if (!gotHit) { - String reason = "title " - + this.description - + " does not contain any of " - + option; - skipMessage(handler, reason); - return false; - } - } else if (null != permittedTitles) { - if (!permittedTitles.contains(this.description)) { - String reason = "titlesList " - + option - + " did not contain " - + this.description; - skipMessage(handler, reason); - return false; - } - } else { - // all other options handled as comma-delimited lists - List<String> specs = LangUtil.commaSplit(option); - // XXX also throw Error on empty specs... - for (Iterator<String> iter = specs.iterator(); iter.hasNext();) { - String spec = (String) iter.next(); - if (null != havePr) { - if (havePr.equals(spec)) { // String.equals() - havePr = null; - } - } else if (keywordMustExist != keywords.contains(spec)) { - String reason = "keyword " + spec - + " was " + (keywordMustExist ? "not found" : "found"); - skipMessage(handler, reason); - return false; - } - } - if (null != havePr) { - skipMessage(handler, "bugId required, but not matched for this test"); - return false; - } - } - } + for (String globalOption : globalOptions) { + String option = globalOption; + if (!option.startsWith(OPTION_PREFIX)) { + throw new Error("only expecting " + OPTION_PREFIX + "..: " + option); + } + option = option.substring(OPTION_PREFIX.length()); + boolean keywordMustExist = false; + List<String> permittedTitles = null; + List<String> permittedTitleStrings = null; + String havePr = null; + if (option.startsWith(REQUIRE_KEYWORDS)) { + option = option.substring(REQUIRE_KEYWORDS.length()); + keywordMustExist = true; + } else if (option.startsWith(SKIP_KEYWORDS)) { + option = option.substring(SKIP_KEYWORDS.length()); + } else if (option.startsWith(TITLE_LIST)) { + option = option.substring(TITLE_LIST.length()); + permittedTitles = getTitles(option); + } else if (option.startsWith(TITLE_FAIL_LIST)) { + option = option.substring(TITLE_FAIL_LIST.length()); + permittedTitles = getTitles(option, true); + } else if (option.startsWith(TITLE_CONTAINS)) { + option = option.substring(TITLE_CONTAINS.length()); + permittedTitleStrings = getTitles(option); + } else if (option.startsWith(PICK_PR)) { + if (0 == bugId) { + skipMessage(handler, "bugId required, but no bugId for this test"); + return false; + } else { + havePr = "" + bugId; + } + option = option.substring(PICK_PR.length()); + } else { + throw new Error("unrecognized suffix: " + globalOption + + " (expecting: " + OPTION_PREFIX + VALID_SUFFIXES + "...)"); + } + if (null != permittedTitleStrings) { + boolean gotHit = false; + for (Iterator<String> iter = permittedTitleStrings.iterator(); + !gotHit && iter.hasNext(); + ) { + String substring = (String) iter.next(); + if (-1 != this.description.indexOf(substring)) { + gotHit = true; + } + } + if (!gotHit) { + String reason = "title " + + this.description + + " does not contain any of " + + option; + skipMessage(handler, reason); + return false; + } + } else if (null != permittedTitles) { + if (!permittedTitles.contains(this.description)) { + String reason = "titlesList " + + option + + " did not contain " + + this.description; + skipMessage(handler, reason); + return false; + } + } else { + // all other options handled as comma-delimited lists + List<String> specs = LangUtil.commaSplit(option); + // XXX also throw Error on empty specs... + for (String spec : specs) { + if (null != havePr) { + if (havePr.equals(spec)) { // String.equals() + havePr = null; + } + } else if (keywordMustExist != keywords.contains(spec)) { + String reason = "keyword " + spec + + " was " + (keywordMustExist ? "not found" : "found"); + skipMessage(handler, reason); + return false; + } + } + if (null != havePr) { + skipMessage(handler, "bugId required, but not matched for this test"); + return false; + } + } + } return true; } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRun.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRun.java index c5d4b0b60..6c8b2ba5f 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRun.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRun.java @@ -134,16 +134,15 @@ public class CompilerRun implements IAjcRun { return new String[0]; } ArrayList result = new ArrayList(); - for (int i = 0; i < inputs.length; i++) { - String input = inputs[i]; - if (null == input) { - continue; - } - File inputFile = new File(baseDir, input); - if (inputFile.canRead() && inputFile.isDirectory()) { - result.add(input); - } - } + for (String input : inputs) { + if (null == input) { + continue; + } + File inputFile = new File(baseDir, input); + if (inputFile.canRead() && inputFile.isDirectory()) { + result.add(input); + } + } return (String[]) result.toArray(new String[0]); } @@ -167,25 +166,24 @@ public class CompilerRun implements IAjcRun { suffixes = temp; } ArrayList result = new ArrayList(); - for (int i = 0; i < inputs.length; i++) { - String input = inputs[i]; - if (null == input) { - continue; - } - if (!ignoreCase) { - input = input.toLowerCase(); - } - for (int j = 0; j < suffixes.length; j++) { - String suffix = suffixes[j]; - if (null == suffix) { - continue; - } - if (input.endsWith(suffix)) { - result.add(input); - break; - } - } - } + for (String s : inputs) { + String input = s; + if (null == input) { + continue; + } + if (!ignoreCase) { + input = input.toLowerCase(); + } + for (String suffix : suffixes) { + if (null == suffix) { + continue; + } + if (input.endsWith(suffix)) { + result.add(input); + break; + } + } + } return (String[]) result.toArray(new String[0]); } @@ -407,12 +405,12 @@ public class CompilerRun implements IAjcRun { return (first != last); } }; - for (int i = 0; i < sourcerootFiles.length; i++) { - FileUtil.deleteContents( - sourcerootFiles[i], - pickIncFiles, - false); - } + for (File sourcerootFile : sourcerootFiles) { + FileUtil.deleteContents( + sourcerootFile, + pickIncFiles, + false); + } if (0 < sourcerootFiles.length) { FileUtil.sleepPastFinalModifiedTime( sourcerootFiles); @@ -469,9 +467,9 @@ public class CompilerRun implements IAjcRun { } if (!LangUtil.isEmpty(argFiles)) { String[] ra = FileUtil.getPaths(argFiles); - for (int j = 0; j < ra.length; j++) { - arguments.add("@" + ra[j]); - } + for (String s : ra) { + arguments.add("@" + s); + } if (!spec.badInput && spec.isStaging) { validator.fail( "warning: files listed in argfiles not staged"); @@ -602,13 +600,11 @@ public class CompilerRun implements IAjcRun { false, slop); if (!LangUtil.isEmpty(found)) { - for (Iterator iter = found.iterator(); - iter.hasNext(); - ) { - MessageUtil.info( - status, - Spec.SEEK_MESSAGE_PREFIX + iter.next()); - } + for (Object o : found) { + MessageUtil.info( + status, + Spec.SEEK_MESSAGE_PREFIX + o); + } } } ICommand compiler = spec.reuseCompiler @@ -1198,16 +1194,14 @@ public class CompilerRun implements IAjcRun { boolean hasInvalidOptions(Values values, TestSetup result) { // not supporting 1.0 options any more - for (Iterator iter = CRSOPTIONS.invalidOptions.iterator(); - iter.hasNext(); - ) { - Option option = (Option) iter.next(); - if (null != values.firstOption(option)) { - result.failureReason = - "invalid option in harness: " + option; - return true; - } - } + for (Object o : CRSOPTIONS.invalidOptions) { + Option option = (Option) o; + if (null != values.firstOption(option)) { + result.failureReason = + "invalid option in harness: " + option; + return true; + } + } return false; } @@ -1243,15 +1237,13 @@ public class CompilerRun implements IAjcRun { return true; } // not supporting 1.0 options any more - for (Iterator iter = CRSOPTIONS.ajc10Options.iterator(); - iter.hasNext(); - ) { - Option option = (Option) iter.next(); - if (null != values.firstOption(option)) { - result.failureReason = "old ajc 1.0 option: " + option; - return true; - } - } + for (Object o : CRSOPTIONS.ajc10Options) { + Option option = (Option) o; + if (null != values.firstOption(option)) { + result.failureReason = "old ajc 1.0 option: " + option; + return true; + } + } return false; } @@ -1771,21 +1763,17 @@ public class CompilerRun implements IAjcRun { }; // among options not permitted: extdirs... - - for (int i = 0; i < options.length; i++) { - crsOptions.addOption(options[i]); - } - for (Iterator iter = compilerOptions.iterator(); - iter.hasNext(); - ) { - crsOptions.addOption((Option) iter.next()); - } + + for (Option option : options) { + crsOptions.addOption(option); + } + for (Object compilerOption : compilerOptions) { + crsOptions.addOption((Option) compilerOption); + } // these are recognized but records with them are skipped - for (Iterator iter = ajc10Options.iterator(); - iter.hasNext(); - ) { - crsOptions.addOption((Option) iter.next()); - } + for (Object ajc10Option : ajc10Options) { + crsOptions.addOption((Option) ajc10Option); + } crsOptions.freeze(); } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java index 1a8873072..12b91679a 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/CompilerRunSpecTest.java @@ -204,17 +204,17 @@ public class CompilerRunSpecTest extends TestCase { Set options = crsOptions.compilerOptions(); assertTrue(null != options); StringBuffer notLoaded = new StringBuffer(); - for (Iterator iter = options.iterator(); iter.hasNext();) { - Option compilerOption = (Option) iter.next(); - if (!(crsOptions.compilerIsLoadable(compilerOption))) { - notLoaded.append(" " + compilerOption); - } else { - String className = crsOptions.compilerClassName(compilerOption); - String argValue = compilerOption.toString(); // XXX snoop - String arg = Option.ON.render(argValue); - checkCompilerOption(arg, className); - } - } + for (Object option : options) { + Option compilerOption = (Option) option; + if (!(crsOptions.compilerIsLoadable(compilerOption))) { + notLoaded.append(" " + compilerOption); + } else { + String className = crsOptions.compilerClassName(compilerOption); + String argValue = compilerOption.toString(); // XXX snoop + String arg = Option.ON.render(argValue); + checkCompilerOption(arg, className); + } + } if (0 < notLoaded.length()) { System.err.println( getClass().getName() @@ -298,12 +298,12 @@ public class CompilerRunSpecTest extends TestCase { new String[] { "-verbose", "-g:vars,source" }, }; // normal - for (int i = 0; i < input.length; i++) { - optionChecker.checkOptions(input[i], input[i]); - } - for (int i = 0; i < literalInput.length; i++) { - optionChecker.checkOptions(literalInput[i], literalInput[i]); - } + for (String[] value : input) { + optionChecker.checkOptions(value, value); + } + for (String[] strings : literalInput) { + optionChecker.checkOptions(strings, strings); + } // force-on String[][] forceInput = duplicate(input, "!"); for (int i = 0; i < input.length; i++) { diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChanges.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChanges.java index 13281607b..95977aeee 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChanges.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/DirChanges.java @@ -238,31 +238,31 @@ public class DirChanges { // final File expDir = ((!doCompare || (null == spec.expDir)) // ? null // : new File(baseDir, spec.expDir)); - for (Iterator iter = pathList.iterator(); iter.hasNext();) { - final String entry = (String) iter.next() ; - String path = entry ; - if (null != spec.defaultSuffix) { - if (".class".equals(spec.defaultSuffix)) { - path = path.replace('.', '/'); - } - path = path + spec.defaultSuffix; - } - File actualFile = new File(baseDir, path); - if (exists != (actualFile.canRead() && actualFile.isFile() - && (expectStartEarlier - ? startTime <= actualFile.lastModified() - : startTime > actualFile.lastModified() - ))) { - failMessage(handler, exists, label, path, actualFile); - if (result) { - result = false; - } - } else if (exists && doCompare && (null != fileChecker)) { - if (!fileChecker.checkFile(handler, path, actualFile) && result) { - result = false; - } - } - } + for (Object o : pathList) { + final String entry = (String) o; + String path = entry; + if (null != spec.defaultSuffix) { + if (".class".equals(spec.defaultSuffix)) { + path = path.replace('.', '/'); + } + path = path + spec.defaultSuffix; + } + File actualFile = new File(baseDir, path); + if (exists != (actualFile.canRead() && actualFile.isFile() + && (expectStartEarlier + ? startTime <= actualFile.lastModified() + : startTime > actualFile.lastModified() + ))) { + failMessage(handler, exists, label, path, actualFile); + if (result) { + result = false; + } + } else if (exists && doCompare && (null != fileChecker)) { + if (!fileChecker.checkFile(handler, path, actualFile) && result) { + result = false; + } + } + } } return result; } @@ -600,12 +600,11 @@ public class DirChanges { return; } LangUtil.throwIaxIfNull(out, "out"); - for (Iterator<DirChanges.Spec> iter = dirChanges.iterator(); iter.hasNext();) { - DirChanges.Spec spec = iter.next(); + for (Spec spec : dirChanges) { if (null == spec) { - continue; - } - spec.writeXml(out); + continue; + } + spec.writeXml(out); } } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java index ac707a183..a0c48878e 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/IncCompilerRun.java @@ -413,11 +413,11 @@ public class IncCompilerRun implements IAjcRun { if (null != items) { String[] classes = XMLWriter.unflattenList(items); if (!LangUtil.isEmpty(classes)) { - for (int i = 0; i < classes.length; i++) { - if (!LangUtil.isEmpty(classes[i])) { - list.add(classes[i]); - } - } + for (String aClass : classes) { + if (!LangUtil.isEmpty(aClass)) { + list.add(aClass); + } + } } } } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java index c891f134c..ee07fe4f6 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/ParseTestCase.java @@ -58,17 +58,17 @@ public class ParseTestCase extends TestCase { Sandbox sandbox = new Sandbox(new File("testdata"), validator); IRunListener listenerNULL = null; ISourceLocation sl = new SourceLocation(suiteFile, 0, 0,0); - for (Iterator iter = tests.iterator(); iter.hasNext();) { - status = new RunStatus(handler, runner); - AjcTest.Spec test = (AjcTest.Spec) iter.next(); - test.setSourceLocation(sl); + for (Object o : tests) { + status = new RunStatus(handler, runner); + AjcTest.Spec test = (AjcTest.Spec) o; + test.setSourceLocation(sl); IRunIterator child = test.makeRunIterator(sandbox, validator); - //test.setup(new String[0], validator); // XXX + //test.setup(new String[0], validator); // XXX //IRun child = runner.wrap(test, null); - // huh? runIterator not generating child status? - //RunStatus childStatus = runner.makeChildStatus(); - runner.runIterator(child, status, listenerNULL); - MessageUtil.print(System.err, status); + // huh? runIterator not generating child status? + //RunStatus childStatus = runner.makeChildStatus(); + runner.runIterator(child, status, listenerNULL); + MessageUtil.print(System.err, status); } } diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/Sandbox.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/Sandbox.java index f7f4df31e..5108444e1 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/Sandbox.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/Sandbox.java @@ -341,13 +341,12 @@ public class Sandbox { ArrayList result = new ArrayList(); NamesFilter filter = new NamesFilter(names); File[] bases = { testBaseDir, sandboxDir }; - for (int i = 0; i < bases.length; i++) { - File base = bases[i]; - if ((null == base) || !base.canRead()) { - continue; - } - result.addAll(Arrays.asList(FileUtil.listFiles(base, filter))); - } + for (File base : bases) { + if ((null == base) || !base.canRead()) { + continue; + } + result.addAll(Arrays.asList(FileUtil.listFiles(base, filter))); + } return (File[]) result.toArray(new File[0]); } File getTestBaseSrcDir(JavaRun caller) { @@ -482,11 +481,10 @@ public class Sandbox { assertState(null != compileClasspath, "classpath not set"); ArrayList result = new ArrayList(); File[] src = compileClasspath; - for (int i = 0; i < src.length; i++) { - File f = src[i]; - if ((null != f) && (f.isDirectory()) && (!readable || f.canRead())) { - result.add(f); - } + for (File f : src) { + if ((null != f) && (f.isDirectory()) && (!readable || f.canRead())) { + result.add(f); + } } if (includeOutput && (null != classesDir) && (!readable || classesDir.canRead())) { @@ -505,16 +503,15 @@ public class Sandbox { assertState(null != compileClasspath, "classpath not set"); ArrayList result = new ArrayList(); File[][] src = new File[][] { compileClasspath, aspectpath }; - for (int i = 0; i < src.length; i++) { - File[] paths = src[i]; - int len = (null == paths ? 0 : paths.length); - for (int j = 0; j < len; j++) { - File f = paths[j]; - if (FileUtil.isZipFile(f) && (!readable || f.canRead())) { - result.add(f); - } + for (File[] paths : src) { + int len = (null == paths ? 0 : paths.length); + for (int j = 0; j < len; j++) { + File f = paths[j]; + if (FileUtil.isZipFile(f) && (!readable || f.canRead())) { + result.add(f); + } } - } + } return (File[]) result.toArray(new File[0]); } @@ -562,11 +559,11 @@ public class Sandbox { if (null != file) { String name = file.getName(); if ((null != name) && (null != names)) { - for (int i = 0; i < names.length; i++) { - if (name.equals(names[i])) { - return true; - } - } + for (String s : names) { + if (name.equals(s)) { + return true; + } + } } } return false; diff --git a/testing/src/test/java/org/aspectj/testing/harness/bridge/Validator.java b/testing/src/test/java/org/aspectj/testing/harness/bridge/Validator.java index 5bb1a15b2..a0b4f5e96 100644 --- a/testing/src/test/java/org/aspectj/testing/harness/bridge/Validator.java +++ b/testing/src/test/java/org/aspectj/testing/harness/bridge/Validator.java @@ -150,8 +150,8 @@ public class Validator { public boolean nullcheck(Collection list, String message) { if (nullcheck((Object) list, message + " list")) { int i = 0; - for (Iterator iter = list.iterator(); iter.hasNext();) { - if (!nullcheck(iter.next(), message + "[" + i++ + "]")) { + for (Object o : list) { + if (!nullcheck(o, message + "[" + i++ + "]")) { return false; } } @@ -286,9 +286,8 @@ public class Validator { public boolean canReadFiles(Collection dirs, String message) { if (nullcheck((Object) dirs, message + " files")) { int i = 0; - for (Iterator iter = dirs.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (! (o instanceof File)) { + for (Object o : dirs) { + if (!(o instanceof File)) { fail(i + ": not a file " + o); } if (!canRead((File) o, message + "[" + i++ + "]")) { @@ -319,9 +318,8 @@ public class Validator { public boolean canReadDirs(Collection dirs, String message) { if (nullcheck((Object) dirs, message + " dirs")) { int i = 0; - for (Iterator iter = dirs.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (! (o instanceof File)) { + for (Object o : dirs) { + if (!(o instanceof File)) { fail(i + ": not a file " + o); } if (!canReadDir((File) o, message + "[" + i++ + "]")) { @@ -353,9 +351,8 @@ public class Validator { public boolean canWriteFiles(Collection dirs, String message) { if (nullcheck((Object) dirs, message + " files")) { int i = 0; - for (Iterator iter = dirs.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (! (o instanceof File)) { + for (Object o : dirs) { + if (!(o instanceof File)) { fail(i + ": not a file " + o); } if (!canWrite((File) o, message + "[" + i++ + "]")) { @@ -387,9 +384,8 @@ public class Validator { public boolean canWriteDirs(Collection dirs, String message) { if (nullcheck((Object) dirs, message + " dirs")) { int i = 0; - for (Iterator iter = dirs.iterator(); iter.hasNext();) { - Object o = iter.next(); - if (! (o instanceof File)) { + for (Object o : dirs) { + if (!(o instanceof File)) { fail(i + ": not a file " + o); } if (!canWriteDir((File) o, message + "[" + i++ + "]")) { diff --git a/testing/src/test/java/org/aspectj/testing/run/RunStatus.java b/testing/src/test/java/org/aspectj/testing/run/RunStatus.java index ac22280ba..272f57103 100644 --- a/testing/src/test/java/org/aspectj/testing/run/RunStatus.java +++ b/testing/src/test/java/org/aspectj/testing/run/RunStatus.java @@ -230,8 +230,8 @@ public class RunStatus implements IRunStatus { } if (includeChildren) { IRunStatus[] kids = getChildren(); - for (int i = 0; i < kids.length; i++) { - if (kids[i].hasAnyMessage(kind, orGreater, true)) { + for (IRunStatus kid : kids) { + if (kid.hasAnyMessage(kind, orGreater, true)) { return true; } } @@ -250,8 +250,8 @@ public class RunStatus implements IRunStatus { } IRunStatus[] kids = getChildren(); - for (int i = 0; i < kids.length; i++) { - result = kids[i].getMessages(kind, orGreater, includeChildren); + for (IRunStatus kid : kids) { + result = kid.getMessages(kind, orGreater, includeChildren); if (!LangUtil.isEmpty(result)) { sink.addAll(Arrays.asList(result)); } @@ -429,8 +429,8 @@ public class RunStatus implements IRunStatus { if ((null != children) && (0 < children.size())) { String label = "### --------- " + name; int index = 0; - for (Iterator iter = children.iterator(); iter.hasNext();) { - IRunStatus childStatus = (IRunStatus) iter.next(); + for (Object child : children) { + IRunStatus childStatus = (IRunStatus) child; String childLabel = "\n" + label + " child[" + index++ + "] " + childStatus.getIdentifier(); sb.append(childLabel + " ---- start\n"); sb.append(childStatus.toString()); diff --git a/testing/src/test/java/org/aspectj/testing/util/BridgeUtil.java b/testing/src/test/java/org/aspectj/testing/util/BridgeUtil.java index a4672b23f..a6e4c7cab 100644 --- a/testing/src/test/java/org/aspectj/testing/util/BridgeUtil.java +++ b/testing/src/test/java/org/aspectj/testing/util/BridgeUtil.java @@ -458,10 +458,10 @@ public class BridgeUtil { final int numTests = numIncomplete + numChildren + numSkips; int numFails = 0; if (!LangUtil.isEmpty(children)) { - for (int i = 0; i < children.length; i++) { - if (!RunValidator.NORMAL.runPassed(children[i])) { - numFails++; - } + for (IRunStatus child : children) { + if (!RunValidator.NORMAL.runPassed(child)) { + numFails++; + } } } final int numPass = children.length - numFails; diff --git a/testing/src/test/java/org/aspectj/testing/util/Diffs.java b/testing/src/test/java/org/aspectj/testing/util/Diffs.java index dd54fa4da..fee19a3e1 100644 --- a/testing/src/test/java/org/aspectj/testing/util/Diffs.java +++ b/testing/src/test/java/org/aspectj/testing/util/Diffs.java @@ -455,8 +455,7 @@ public class Diffs { Collections.sort(sink, MESSAGE_LINEKIND); return sink; } - for (int i = 0; i < source.length; i++) { - IMessage message = source[i]; + for (IMessage message : source) { IMessage.Kind mkind = message.getKind(); boolean skipping = false; for (int j = 0; !skipping && (j < skip.length); j++) { @@ -521,12 +520,12 @@ public class Diffs { LangUtil.throwIaxIfNull(handler, "handler"); LangUtil.throwIaxIfNull(kind, "kind"); if (different) { - for (Iterator iter = missing.iterator(); iter.hasNext();) { - String s = MessageUtil.renderMessage((IMessage) iter.next()); + for (Object value : missing) { + String s = MessageUtil.renderMessage((IMessage) value); MessageUtil.fail(handler, "missing " + label + ": " + s); } - for (Iterator iter = unexpected.iterator(); iter.hasNext();) { - String s = MessageUtil.renderMessage((IMessage) iter.next()); + for (Object o : unexpected) { + String s = MessageUtil.renderMessage((IMessage) o); MessageUtil.fail(handler, "unexpected " + label + ": " + s); } } diff --git a/testing/src/test/java/org/aspectj/testing/util/FileUtil.java b/testing/src/test/java/org/aspectj/testing/util/FileUtil.java index 86db6baa5..a47f694e4 100644 --- a/testing/src/test/java/org/aspectj/testing/util/FileUtil.java +++ b/testing/src/test/java/org/aspectj/testing/util/FileUtil.java @@ -133,12 +133,11 @@ public class FileUtil { // normalize sources to ignore final ArrayList expected = (!checkExpected ? null : new ArrayList()); if (checkExpected) { - for (int i = 0; i < expectedPaths.length; i++) { - String srcPath = expectedPaths[i]; - if (!LangUtil.isEmpty(srcPath)) { - expected.add(org.aspectj.util.FileUtil.weakNormalize(srcPath)); - } - } + for (String srcPath : expectedPaths) { + if (!LangUtil.isEmpty(srcPath)) { + expected.add(org.aspectj.util.FileUtil.weakNormalize(srcPath)); + } + } } // gather, normalize paths changed @@ -166,18 +165,16 @@ public class FileUtil { return false; } } else { - for (Iterator iter = expected.iterator(); - iter.hasNext(); - ) { - String exp = (String) iter.next(); - if (path.startsWith(exp)) { - String suffix = path.substring(exp.length()); - if (-1 == suffix.indexOf("/")) { // normalized... - expected.remove(path); - // found - do not add to unexpected - return false; - } - } + for (Object o : expected) { + String exp = (String) o; + if (path.startsWith(exp)) { + String suffix = path.substring(exp.length()); + if (-1 == suffix.indexOf("/")) { // normalized... + expected.remove(path); + // found - do not add to unexpected + return false; + } + } } } } @@ -292,26 +289,26 @@ public class FileUtil { // go through files first File[] files = file.listFiles(ValidFileFilter.FILE_EXISTS); if (null != files) { - for (int i = 0; i < files.length; i++) { - if (!fileFilter.accept(files[i])) { - return false; - } - } + for (File value : files) { + if (!fileFilter.accept(value)) { + return false; + } + } } // now recurse to handle directories File[] dirs = file.listFiles(ValidFileFilter.DIR_EXISTS); if (null != dirs) { - for (int i = 0; i < dirs.length; i++) { - if (userRecursion) { - if (!fileFilter.accept(dirs[i])) { - return false; - } - } else { - if (!descendFileTree(dirs[i], fileFilter,userRecursion)) { - return false; - } - } - } + for (File dir : dirs) { + if (userRecursion) { + if (!fileFilter.accept(dir)) { + return false; + } + } else { + if (!descendFileTree(dir, fileFilter, userRecursion)) { + return false; + } + } + } } } // readable directory (ignore unreadable ones) return true; diff --git a/testing/src/test/java/org/aspectj/testing/util/LangUtil.java b/testing/src/test/java/org/aspectj/testing/util/LangUtil.java index 2baf81c48..e78ec84c8 100644 --- a/testing/src/test/java/org/aspectj/testing/util/LangUtil.java +++ b/testing/src/test/java/org/aspectj/testing/util/LangUtil.java @@ -406,18 +406,18 @@ public class LangUtil { twoList.addAll(org.aspectj.util.LangUtil.arrayAsList(two)); ArrayList result = new ArrayList(); if (null != one) { - for (int i = 0; i < one.length; i++) { - if (null != one[i]) { - twoList.remove(one[i]); - result.add(one[i]); - } - } + for (String s : one) { + if (null != s) { + twoList.remove(s); + result.add(s); + } + } } - for (Iterator iterator = twoList.iterator(); iterator.hasNext(); ) { - String element = (String) iterator.next(); + for (Object o : twoList) { + String element = (String) o; if (null != element) { - result.add(element); - } + result.add(element); + } } return (String[]) result.toArray(NONE); } @@ -425,19 +425,19 @@ public class LangUtil { public static Properties combine(Properties dest, Properties add, boolean respectExisting) { // XXX if (null == add) return dest; if (null == dest) return add; - for (Iterator iterator = add.keySet().iterator(); iterator.hasNext(); ) { - String key = (String) iterator.next(); - if (null == key) { - continue; - } - String value = add.getProperty(key); - if (null == value) { - continue; - } - if (! respectExisting || (null == dest.getProperty(key))) { - dest.setProperty(key, value); - } - } + for (Object o : add.keySet()) { + String key = (String) o; + if (null == key) { + continue; + } + String value = add.getProperty(key); + if (null == value) { + continue; + } + if (!respectExisting || (null == dest.getProperty(key))) { + dest.setProperty(key, value); + } + } return dest; } @@ -547,22 +547,22 @@ public class LangUtil { public static void loadClasses(String[] args, StringBuffer out, StringBuffer err) { if (null != args) { - for (int i = 0; i < args.length; i++) { - try { - Class c = Class.forName(args[i]); - if (null != out) { - out.append("\n"); - out.append(args[i]); - out.append(": "); - out.append(c.getName()); - } - } catch (Throwable t) { - if (null != err) { - err.append("\n"); - FileUtil.render(t, err); - } - } - } + for (String arg : args) { + try { + Class c = Class.forName(arg); + if (null != out) { + out.append("\n"); + out.append(arg); + out.append(": "); + out.append(c.getName()); + } + } catch (Throwable t) { + if (null != err) { + err.append("\n"); + FileUtil.render(t, err); + } + } + } } } @@ -577,20 +577,20 @@ public class LangUtil { } int length = path.length() - ".class".length(); path = path.substring(prefix.length()+1, length); - for (int i = 0; i < SEPS.length; i++) { - path = path.replace(SEPS[i], '.'); - } + for (char sep : SEPS) { + path = path.replace(sep, '.'); + } return path; } public static void main (String[] args) { // todo remove as testing StringBuffer err = new StringBuffer(); StringBuffer out = new StringBuffer(); - for (int i = 0; i < args.length; i++) { - String[] names = classesIn(new File(args[i])); - System.err.println(args[i] + " -> " + render(names)); - loadClasses(names, out, err); - } + for (String arg : args) { + String[] names = classesIn(new File(arg)); + System.err.println(arg + " -> " + render(names)); + loadClasses(names, out, err); + } if (0 < err.length()) { System.err.println(err.toString()); } @@ -887,8 +887,7 @@ public class LangUtil { return; } BitSet actualExpected = new BitSet(); - for (int i = 0; i < expectedListIn.size(); i++) { - Object expect = expectedListIn.get(i); + for (Object expect : expectedListIn) { int loc = actualListIn.indexOf(expect); if (-1 == loc) { if (null != missingListOut) { @@ -962,19 +961,18 @@ public class LangUtil { // messages on the same line, but with different text content. while (actualIter.hasNext()) { act = actualIter.next(); - for (Iterator expectedIter = expected.iterator(); expectedIter.hasNext();) { - Object exp = expectedIter.next(); - // if actual matches expected remove actual from extraListOut, and - // remove expected from missingListOut - int diff = comparator.compare(exp,act); - if (diff == 0) { - extraListOut.remove(act); - missingListOut.remove(exp); - } else if (diff > 0) { - // since list is sorted, there can be no more matches... - break; - } - } + for (Object exp : expected) { + // if actual matches expected remove actual from extraListOut, and + // remove expected from missingListOut + int diff = comparator.compare(exp, act); + if (diff == 0) { + extraListOut.remove(act); + missingListOut.remove(exp); + } else if (diff > 0) { + // since list is sorted, there can be no more matches... + break; + } + } } // while (((null != act) || actualIter.hasNext()) diff --git a/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java index 8131fdf7e..30f2a0b06 100644 --- a/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java +++ b/testing/src/test/java/org/aspectj/testing/util/LangUtilTest.java @@ -89,8 +89,8 @@ public class LangUtilTest extends TestCase { , new FTest("[1,2]", new String[] {"1,2"}, LIST) , new FTest("[1, 2, 3]", new String[] {"1","2","3"}, LIST) }; - for (int i = 0; i < tests.length; i++) { - checkUnflatten(tests[i]); + for (FTest test : tests) { + checkUnflatten(test); } } diff --git a/testing/src/test/java/org/aspectj/testing/util/LineReader.java b/testing/src/test/java/org/aspectj/testing/util/LineReader.java index a6af8266a..0c75aa9d1 100644 --- a/testing/src/test/java/org/aspectj/testing/util/LineReader.java +++ b/testing/src/test/java/org/aspectj/testing/util/LineReader.java @@ -164,21 +164,21 @@ public class LineReader extends LineNumberReader { if (result == null) return null; result = result.trim(); - for (int i = 0; i < eolComments.length; i++) { - int loc = result.indexOf(eolComments[i]); - if (-1 != loc) { - result = result.substring(0, loc); - break; - } - } + for (String eolComment : eolComments) { + int loc = result.indexOf(eolComment); + if (-1 != loc) { + result = result.substring(0, loc); + break; + } + } len = result.length(); if (0 < len) { - for (int i = 0; i < leadComments.length; i++) { - if (result.startsWith(leadComments[i])) { - result = ""; - break; - } - } + for (String leadComment : leadComments) { + if (result.startsWith(leadComment)) { + result = ""; + break; + } + } len = result.length(); } len = result.length(); diff --git a/testing/src/test/java/org/aspectj/testing/util/LinkCheck.java b/testing/src/test/java/org/aspectj/testing/util/LinkCheck.java index 3317f7746..380766a3b 100644 --- a/testing/src/test/java/org/aspectj/testing/util/LinkCheck.java +++ b/testing/src/test/java/org/aspectj/testing/util/LinkCheck.java @@ -226,24 +226,22 @@ public class LinkCheck { messages.checkingLinks(linksToCheck.size()); list.clear(); list.addAll(linksToCheck); - for (Iterator<Link> iter = list.iterator(); iter.hasNext();) { - final Link link = iter.next(); - String urlString = link.url.toString(); - if (!checkedUrls.contains(urlString)) { - checkedUrls.add(urlString); - messages.checkingLink(link); - checkLink(link); - } - } + for (final Link link : list) { + String urlString = link.url.toString(); + if (!checkedUrls.contains(urlString)) { + checkedUrls.add(urlString); + messages.checkingLink(link); + checkLink(link); + } + } linksToCheck.removeAll(list); } // now check that all named references are accounted for - for (Iterator<String> iter = refsToCheck.iterator(); iter.hasNext();) { - String ref = iter.next(); - if (!validRefs.contains(ref)) { - messages.namedReferenceNotFound(ref); - } - } + for (String ref : refsToCheck) { + if (!validRefs.contains(ref)) { + messages.namedReferenceNotFound(ref); + } + } } /** @return null if link known or if unable to create */ diff --git a/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java b/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java index 571633a0c..954ab38c0 100644 --- a/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java +++ b/testing/src/test/java/org/aspectj/testing/util/MessageUtilTest.java @@ -104,25 +104,20 @@ public class MessageUtilTest extends TestCase { MessageHandler getSampleMessages() { MessageHandler result = new MessageHandler(); - for (Iterator kinds = IMessage.KINDS.iterator(); kinds.hasNext();) { - IMessage.Kind kind = (IMessage.Kind) kinds.next(); - for (Iterator locs = getSampleLocations().iterator(); locs.hasNext();) { - ISourceLocation sourceLoc = (ISourceLocation) locs.next(); - for (Iterator texts = getSampleMessageTexts().iterator(); - texts.hasNext(); - ) { - String text = (String) texts.next(); - for (Iterator exs = getSampleExceptions().iterator(); - exs.hasNext(); - ) { - Throwable thrown = (Throwable) exs.next(); - result.handleMessage(new Message(text, kind, thrown, sourceLoc)); + for (IMessage.Kind kind : IMessage.KINDS) { + for (Object item : getSampleLocations()) { + ISourceLocation sourceLoc = (ISourceLocation) item; + for (Object value : getSampleMessageTexts()) { + String text = (String) value; + for (Object o : getSampleExceptions()) { + Throwable thrown = (Throwable) o; + result.handleMessage(new Message(text, kind, thrown, sourceLoc)); } - result.handleMessage(new Message(text, kind, null, sourceLoc)); + result.handleMessage(new Message(text, kind, null, sourceLoc)); } - result.handleMessage(new Message("", kind, null, sourceLoc)); + result.handleMessage(new Message("", kind, null, sourceLoc)); } - result.handleMessage(new Message("", kind, null, null)); + result.handleMessage(new Message("", kind, null, null)); } return result; } diff --git a/testing/src/test/java/org/aspectj/testing/util/SFileReader.java b/testing/src/test/java/org/aspectj/testing/util/SFileReader.java index eecf2d304..afa66d46f 100644 --- a/testing/src/test/java/org/aspectj/testing/util/SFileReader.java +++ b/testing/src/test/java/org/aspectj/testing/util/SFileReader.java @@ -41,15 +41,15 @@ public class SFileReader { ArrayList result = new ArrayList(); ObjectChecker collector = new StandardObjectChecker(String.class, result); SFileReader me = new SFileReader(null); - for (int i = 0; i < args.length; i++) { - Node node = me.readNodes(new File(args[i]), null, true, System.err); - if (!Node.visit(node, collector, null)) { - System.err.println("halted during copy of " +args[i]); - } else { - String s = org.aspectj.testing.util.LangUtil.debugStr(null, "\n ", null, - null, result.toArray(), "\n ", ""); - System.err.println(args[i] + ": " + s); - } + for (String arg : args) { + Node node = me.readNodes(new File(arg), null, true, System.err); + if (!Node.visit(node, collector, null)) { + System.err.println("halted during copy of " + arg); + } else { + String s = org.aspectj.testing.util.LangUtil.debugStr(null, "\n ", null, + null, result.toArray(), "\n ", ""); + System.err.println(arg + ": " + s); + } } } diff --git a/testing/src/test/java/org/aspectj/testing/util/StructureModelUtil.java b/testing/src/test/java/org/aspectj/testing/util/StructureModelUtil.java index cd3727e9b..1763e73dd 100644 --- a/testing/src/test/java/org/aspectj/testing/util/StructureModelUtil.java +++ b/testing/src/test/java/org/aspectj/testing/util/StructureModelUtil.java @@ -146,12 +146,11 @@ public class StructureModelUtil { public static Set getAspectsAffectingPackage(IProgramElement packageNode) { List<IProgramElement> files = StructureModelUtil.getFilesInPackage(packageNode); Set aspects = new HashSet(); - for (Iterator<IProgramElement> it = files.iterator(); it.hasNext();) { - IProgramElement fileNode = (IProgramElement) it.next(); + for (IProgramElement fileNode : files) { Map adviceMap = getLinesToAspectMap(fileNode.getSourceLocation().getSourceFile().getAbsolutePath()); Collection values = adviceMap.values(); - for (Iterator it2 = values.iterator(); it2.hasNext();) { - aspects.add(it2.next()); + for (Object value : values) { + aspects.add(value); } } return aspects; @@ -182,8 +181,7 @@ public class StructureModelUtil { matches.add(o); } - for (Iterator it = node.getChildren().iterator(); it.hasNext();) { - IProgramElement nextNode = (IProgramElement) it.next(); + for (IProgramElement nextNode : node.getChildren()) { getPackagesHelper(nextNode, kind, prename, matches); } @@ -251,8 +249,7 @@ public class StructureModelUtil { packageContents = packageNode.getChildren(); } List<IProgramElement> files = new ArrayList<IProgramElement>(); - for (Iterator<IProgramElement> it = packageContents.iterator(); it.hasNext();) { - IProgramElement packageItem = (IProgramElement) it.next(); + for (IProgramElement packageItem : packageContents) { if (packageItem.getKind() == IProgramElement.Kind.FILE_JAVA || packageItem.getKind() == IProgramElement.Kind.FILE_ASPECTJ) { files.add(packageItem); diff --git a/testing/src/test/java/org/aspectj/testing/util/TestClassLoader.java b/testing/src/test/java/org/aspectj/testing/util/TestClassLoader.java index dd9c10c8f..8a753dfc7 100644 --- a/testing/src/test/java/org/aspectj/testing/util/TestClassLoader.java +++ b/testing/src/test/java/org/aspectj/testing/util/TestClassLoader.java @@ -119,12 +119,12 @@ public class TestClassLoader extends URLClassLoader { /** @return null if class not found or byte[] of class otherwise */ private byte[] readClass(String className) throws ClassNotFoundException { final String fileName = className.replace('.', '/')+".class"; - for (Iterator iter = dirs.iterator(); iter.hasNext();) { - File file = new File((File) iter.next(), fileName); - if (file.canRead()) { - return getClassData(file); - } - } + for (Object dir : dirs) { + File file = new File((File) dir, fileName); + if (file.canRead()) { + return getClassData(file); + } + } return null; } diff --git a/testing/src/test/java/org/aspectj/testing/util/TestDiffs.java b/testing/src/test/java/org/aspectj/testing/util/TestDiffs.java index 54f72e9b9..dbb0c1bb1 100644 --- a/testing/src/test/java/org/aspectj/testing/util/TestDiffs.java +++ b/testing/src/test/java/org/aspectj/testing/util/TestDiffs.java @@ -125,8 +125,8 @@ public class TestDiffs { // XXX pretty dumb implementation final String suffix = " " + label; final String LABEL = list.size() + suffix; out.println("## START " + LABEL); - for (Iterator iter = list.iterator(); iter.hasNext();) { - TestResult result = (TestResult) iter.next(); + for (Object o : list) { + TestResult result = (TestResult) o; out.println(" " + result.test + " ## " + suffix); } out.println("## END " + LABEL); @@ -146,14 +146,12 @@ public class TestDiffs { // XXX pretty dumb implementation if (!LangUtil.isEmpty(input) && !LangUtil.isEmpty(trim)) { for (ListIterator iter = result.listIterator(); iter.hasNext();) { TestResult inputItem = (TestResult) iter.next(); - for (Iterator iterator = trim.iterator(); - iterator.hasNext(); - ) { - TestResult trimItem = (TestResult) iterator.next(); + for (Object o : trim) { + TestResult trimItem = (TestResult) o; if (inputItem.test.equals(trimItem.test)) { - iter.remove(); - break; - } + iter.remove(); + break; + } } } } @@ -163,13 +161,13 @@ public class TestDiffs { // XXX pretty dumb implementation /** split input List by whether the TestResult element passed or failed */ private static void split(List input, ArrayList pass, ArrayList fail) { - for (ListIterator iter = input.listIterator(); iter.hasNext();) { - TestResult result = (TestResult) iter.next(); - if (result.pass) { - pass.add(result); - } else { - fail.add(result); - } + for (Object o : input) { + TestResult result = (TestResult) o; + if (result.pass) { + pass.add(result); + } else { + fail.add(result); + } } } diff --git a/testing/src/test/java/org/aspectj/testing/util/options/Option.java b/testing/src/test/java/org/aspectj/testing/util/options/Option.java index f8ea3d9c4..b9c6d2cab 100644 --- a/testing/src/test/java/org/aspectj/testing/util/options/Option.java +++ b/testing/src/test/java/org/aspectj/testing/util/options/Option.java @@ -226,11 +226,11 @@ public class Option implements Comparable { return "no input permitted at " + position; } String[] permitted = permittedArguments[position]; - for (int i = 0; i < permitted.length; i++) { - if (input.equals(permitted[i])) { - return null; - } - } + for (String s : permitted) { + if (input.equals(s)) { + return null; + } + } return input + " not permitted, expecting one of " + Arrays.asList(permitted); } diff --git a/testing/src/test/java/org/aspectj/testing/util/options/Options.java b/testing/src/test/java/org/aspectj/testing/util/options/Options.java index f3e52767f..92e84c106 100644 --- a/testing/src/test/java/org/aspectj/testing/util/options/Options.java +++ b/testing/src/test/java/org/aspectj/testing/util/options/Options.java @@ -141,13 +141,13 @@ public class Options { private Option.Value firstMatch(String value) { LangUtil.throwIaxIfNull(value, "value"); // ArrayList list = new ArrayList(); - for (Iterator iter = options.iterator(); iter.hasNext();) { - Option option = (Option) iter.next(); - Option.Value result = option.acceptValue(value); - if (null != result) { - return result; - } - } + for (Object o : options) { + Option option = (Option) o; + Option.Value result = option.acceptValue(value); + if (null != result) { + return result; + } + } return null; } } diff --git a/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java index bd7d98613..5c380d739 100644 --- a/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java +++ b/testing/src/test/java/org/aspectj/testing/util/options/OptionsTest.java @@ -473,9 +473,9 @@ public class OptionsTest extends TestCase { new String[] { "-g:vars,source" }, new String[] { "-verbose", "-g:vars,source" }, }; - for (int i = 0; i < input.length; i++) { - optionChecker.checkOptions(input[i], input[i]); - } + for (String[] strings : input) { + optionChecker.checkOptions(strings, strings); + } } private OptionChecker getOptionChecker() { diff --git a/testing/src/test/java/org/aspectj/testing/util/options/Values.java b/testing/src/test/java/org/aspectj/testing/util/options/Values.java index d21f03165..7a04fbed0 100644 --- a/testing/src/test/java/org/aspectj/testing/util/options/Values.java +++ b/testing/src/test/java/org/aspectj/testing/util/options/Values.java @@ -63,11 +63,11 @@ public class Values { input = new Value[length]; length = 0; Value[] temp; - for (int i = 0; i < values.length; i++) { - temp = values[i].asArray(); - System.arraycopy(temp, 0, input, length, temp.length); - length += temp.length; - } + for (Values value : values) { + temp = value.asArray(); + System.arraycopy(temp, 0, input, length, temp.length); + length += temp.length; + } } return new Values(input); } @@ -260,19 +260,19 @@ public class Values { throw new IllegalArgumentException( "expecting force-off: " + value); } - for (int i = 0; i < matches.length; i++) { - Option.Value match = input[matches[i]]; - if ((null != match) && value.sameValueIdentifier(match)) { - if (match.prefix.forceOn()) { - return "force conflict between " - + value - + " and " - + match; - } else { - input[matches[i]] = null; // unset matches[i]? - } - } - } + for (int j : matches) { + Value match = input[j]; + if ((null != match) && value.sameValueIdentifier(match)) { + if (match.prefix.forceOn()) { + return "force conflict between " + + value + + " and " + + match; + } else { + input[j] = null; // unset matches[i]? + } + } + } return null; } @@ -388,22 +388,22 @@ public class Values { */ private static String[] render(Value[] values) { ArrayList list = new ArrayList(); - for (int i = 0; i < values.length; i++) { - if (null != values[i]) { - String[] output = values[i].unflatten(); - if (LangUtil.isEmpty(output)) { - throw new Error("no output for " + values[i]); - } - - String s = values[i].prefix.render(output[0]); - if (null != s) { // this means the prefix is set - list.add(s); - for (int j = 1; j < output.length; j++) { - list.add(output[j]); - } - } - } - } + for (Value value : values) { + if (null != value) { + String[] output = value.unflatten(); + if (LangUtil.isEmpty(output)) { + throw new Error("no output for " + value); + } + + String s = value.prefix.render(output[0]); + if (null != s) { // this means the prefix is set + list.add(s); + for (int j = 1; j < output.length; j++) { + list.add(output[j]); + } + } + } + } return (String[]) list.toArray(new String[list.size()]); } @@ -545,34 +545,34 @@ public class Values { protected Option.Value[] find(Selector filter, boolean findAll) { LangUtil.throwIaxIfNull(filter, "filter"); ArrayList result = new ArrayList(); - for (int i = 0; i < values.length; i++) { - final boolean accepted; - try { - accepted = filter.accept(values[i]); - } catch (Error e) { - if (Selector.STOP != e) { - throw e; - } - break; - } - if (accepted) { - result.add(values[i]); - if (findAll != FIND_ALL) { - break; - } - } - } + for (Value value : values) { + final boolean accepted; + try { + accepted = filter.accept(value); + } catch (Error e) { + if (Selector.STOP != e) { + throw e; + } + break; + } + if (accepted) { + result.add(value); + if (findAll != FIND_ALL) { + break; + } + } + } return toArray(result); } private Option.Value[] valuesNotNull() { if (null == valuesNotNull) { ArrayList list = new ArrayList(); - for (int i = 0; i < this.values.length; i++) { - if (null != this.values[i]) { - list.add(this.values[i]); - } - } + for (Value value : this.values) { + if (null != value) { + list.add(value); + } + } valuesNotNull = toArray(list); } return valuesNotNull; diff --git a/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReader.java b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReader.java index 62e3fd186..3ab25c088 100644 --- a/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReader.java +++ b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReader.java @@ -462,21 +462,21 @@ public class AjcSpecXmlReader { "../../../tests", "tests", "modules/tests" }; File baseDir; - for (int j = 0; j < baseDirs.length; j++) { - baseDir = baseDirs[j]; - if (!isDir(baseDir)) { - continue; - } - for (int i = 0; i < locations.length; i++) { - File dir = new File(baseDir, locations[i]); - if (isDir(dir)) { - File temp = new File(dir, NAME); - if (temp.isFile() && temp.canRead()) { - return temp.getPath(); - } - } - } - } + for (File file : baseDirs) { + baseDir = file; + if (!isDir(baseDir)) { + continue; + } + for (String location : locations) { + File dir = new File(baseDir, location); + if (isDir(dir)) { + File temp = new File(dir, NAME); + if (temp.isFile() && temp.canRead()) { + return temp.getPath(); + } + } + } + } return null; } public InputSource resolveEntity( diff --git a/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java index 397e8ccfa..796bf0399 100644 --- a/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java +++ b/testing/src/test/java/org/aspectj/testing/xml/AjcSpecXmlReaderTest.java @@ -51,8 +51,7 @@ public class AjcSpecXmlReaderTest extends TestCase { public void tearDown() { if (!LangUtil.isEmpty(tempFiles)) { - for (Iterator<File> iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); + for (File file : tempFiles) { if (file.canRead()) { file.delete(); } @@ -66,23 +65,23 @@ public class AjcSpecXmlReaderTest extends TestCase { AjcSpecXmlReader.BProps[] expected = AjcSpecXmlReader.expectedProperties(); PropertyDescriptor[] des; - for (int i = 0; i < expected.length; i++) { - Class<?> clazz = expected[i].cl; - BeanInfo beanInfo = Introspector.getBeanInfo(clazz); - assertTrue(null != beanInfo); - des = beanInfo.getPropertyDescriptors(); - for (int j = 0; j < expected[i].props.length; j++) { - String name = expected[i].props[j]; - String fqn = clazz.getName() + "." + name; - boolean gotIt = false; - for (int k = 0; k < des.length; k++) { - String desName = des[k].getName(); - if (name.equals(desName)) { - assertTrue(fqn, null != des[k].getWriteMethod()); - gotIt = true; - } - } - assertTrue("no such property: " + fqn, gotIt); + for (AjcSpecXmlReader.BProps bProps : expected) { + Class<?> clazz = bProps.cl; + BeanInfo beanInfo = Introspector.getBeanInfo(clazz); + assertTrue(null != beanInfo); + des = beanInfo.getPropertyDescriptors(); + for (int j = 0; j < bProps.props.length; j++) { + String name = bProps.props[j]; + String fqn = clazz.getName() + "." + name; + boolean gotIt = false; + for (PropertyDescriptor de : des) { + String desName = de.getName(); + if (name.equals(desName)) { + assertTrue(fqn, null != de.getWriteMethod()); + gotIt = true; + } + } + assertTrue("no such property: " + fqn, gotIt); } } @@ -140,9 +139,9 @@ public class AjcSpecXmlReaderTest extends TestCase { assertTrue("CloneNotSupportedException: " + e.getMessage(), false); } - for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) { - iter.next().delete(); - } + for (File file : toDelete) { + file.delete(); + } } void checkRoundTrip(String path) throws IOException, Exception { @@ -199,9 +198,9 @@ public class AjcSpecXmlReaderTest extends TestCase { //System.err.println("----------------------- suite2 " + xml2Path); AjcSpecTest.sameAjcSuiteSpec(suite1, suite2, this); AjcSpecTest.sameAjcSuiteSpec(suite0, suite2, this); - - for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) { - iter.next().delete(); + + for (File file : toDelete) { + file.delete(); } } } diff --git a/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java b/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java index 6d0eeffff..342484a76 100644 --- a/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java +++ b/testing/src/test/java/org/aspectj/testing/xml/MessageListXmlReaderTest.java @@ -38,8 +38,8 @@ public class MessageListXmlReaderTest extends TestCase { public void tearDown() { if (!LangUtil.isEmpty(tempFiles)) { - for (Iterator iter = tempFiles.iterator(); iter.hasNext();) { - File file = (File) iter.next(); + for (Object tempFile : tempFiles) { + File file = (File) tempFile; if (file.canRead()) { file.delete(); } diff --git a/testing/src/test/java/org/aspectj/testing/xml/SoftMessage.java b/testing/src/test/java/org/aspectj/testing/xml/SoftMessage.java index 9a39d0cc8..2241904bd 100644 --- a/testing/src/test/java/org/aspectj/testing/xml/SoftMessage.java +++ b/testing/src/test/java/org/aspectj/testing/xml/SoftMessage.java @@ -64,8 +64,8 @@ public class SoftMessage implements IMessage { return; } List list = messages.getUnmodifiableListView(); - for (Iterator iter = list.iterator(); iter.hasNext();) { - writeXml(out, (IMessage) iter.next()); + for (Object o : list) { + writeXml(out, (IMessage) o); } } @@ -77,8 +77,8 @@ public class SoftMessage implements IMessage { if ((null == out) || (null == messages)) { return; } - for (int i = 0; i < messages.length; i++) { - writeXml(out, messages[i]); + for (IMessage iMessage : messages) { + writeXml(out, iMessage); } } @@ -125,9 +125,9 @@ public class SoftMessage implements IMessage { List extras = message.getExtraSourceLocations(); if (!LangUtil.isEmpty(extras)) { out.endAttributes(); - for (Iterator iter = extras.iterator(); iter.hasNext();) { - /*ISourceLocation element = (ISourceLocation)*/ iter.next(); - SoftSourceLocation.writeXml(out, sl); + for (Object extra : extras) { + /*ISourceLocation element = (ISourceLocation)*/ + SoftSourceLocation.writeXml(out, sl); } } out.endElement(elementName); diff --git a/testing/src/test/java/org/aspectj/testing/xml/XMLWriter.java b/testing/src/test/java/org/aspectj/testing/xml/XMLWriter.java index 422576c56..eaa42326e 100644 --- a/testing/src/test/java/org/aspectj/testing/xml/XMLWriter.java +++ b/testing/src/test/java/org/aspectj/testing/xml/XMLWriter.java @@ -89,11 +89,11 @@ public class XMLWriter { if (null != input) { String[] items = XMLWriter.unflattenList(input); if (!LangUtil.isEmpty(items)) { - for (int i = 0; i < items.length; i++) { - if (!LangUtil.isEmpty(items[i])) { - list.add(items[i]); - } - } + for (String item : items) { + if (!LangUtil.isEmpty(item)) { + list.add(item); + } + } } } } @@ -124,20 +124,19 @@ public class XMLWriter { StringBuffer sb = new StringBuffer(); if (null != list) { boolean printed = false; - for (int i = 0; i < list.length; i++) { - Object o = list[i]; - if (null != o) { - if (printed) { - sb.append(","); - } else { - printed = true; - } - String s = o.toString(); - if (-1 != s.indexOf(",")) { - throw new IllegalArgumentException("comma in " + s); - } - sb.append(s); - } + for (Object o : list) { + if (null != o) { + if (printed) { + sb.append(","); + } else { + printed = true; + } + String s = o.toString(); + if (-1 != s.indexOf(",")) { + throw new IllegalArgumentException("comma in " + s); + } + sb.append(s); + } } } return sb.toString(); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc150/Ajc150Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc150/Ajc150Tests.java index cde62fe51..c105e881d 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc150/Ajc150Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc150/Ajc150Tests.java @@ -358,8 +358,7 @@ public class Ajc150Tests extends org.aspectj.testing.XMLBasedAjcTestCase { boolean f = false; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "PR82570_1"); Method[] meths = jc.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (f) System.err.println("Line number table for " + method.getName() + method.getSignature() + " = " + method.getLineNumberTable()); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc150/Annotations.java b/tests/src/test/java/org/aspectj/systemtest/ajc150/Annotations.java index 0c44996cb..04797eb9f 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc150/Annotations.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc150/Annotations.java @@ -49,10 +49,9 @@ public class Annotations extends XMLBasedAjcTestCase { JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Program"); Method[] meths = jc.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (method.getName().equals("m1")) { - assertTrue("Didn't have annotations - were they lost? method="+method.getName(),method.getAnnotations().length==1); + assertTrue("Didn't have annotations - were they lost? method=" + method.getName(), method.getAnnotations().length == 1); } } } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericITDsDesign.java b/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericITDsDesign.java index d6e4b7112..210f5f44d 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericITDsDesign.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericITDsDesign.java @@ -59,8 +59,7 @@ public class GenericITDsDesign extends XMLBasedAjcTestCase { JavaClass clazz = getClassFromDisk(ajc, classname); Signature sigAttr = null; Attribute[] attrs = clazz.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals("Signature")) { sigAttr = (Signature) attribute; } @@ -87,14 +86,14 @@ public class GenericITDsDesign extends XMLBasedAjcTestCase { private BcelTypeMunger getMungerFromLine(String classname, int linenumber) { List allMungers = getTypeMunger(classname); - for (Iterator iter = allMungers.iterator(); iter.hasNext();) { - BcelTypeMunger element = (BcelTypeMunger) iter.next(); + for (Object munger : allMungers) { + BcelTypeMunger element = (BcelTypeMunger) munger; if (element.getMunger().getSourceLocation().getLine() == linenumber) { return element; } } - for (Iterator iter = allMungers.iterator(); iter.hasNext();) { - BcelTypeMunger element = (BcelTypeMunger) iter.next(); + for (Object allMunger : allMungers) { + BcelTypeMunger element = (BcelTypeMunger) allMunger; System.err.println("Line: " + element.getMunger().getSourceLocation().getLine() + " > " + element); } fail("Couldn't find a type munger from line " + linenumber + " in class " + classname); @@ -105,8 +104,7 @@ public class GenericITDsDesign extends XMLBasedAjcTestCase { JavaClass theClass = getClassFromDisk(ajc, classname); Hashtable<String,Field> retval = new Hashtable<>(); org.aspectj.apache.bcel.classfile.Field[] fs = theClass.getFields(); - for (int i = 0; i < fs.length; i++) { - Field field = fs[i]; + for (Field field : fs) { retval.put(field.getName(), field); } return retval; diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericsTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericsTests.java index 34bdd455c..847f67149 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericsTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc150/GenericsTests.java @@ -886,10 +886,10 @@ public class GenericsTests extends XMLBasedAjcTestCase { Class<?> clz = Class.forName(classname,false,cl); java.lang.reflect.Method[] ms = clz.getDeclaredMethods(); if (ms!=null) { - for (int i =0;i<ms.length;i++) { - String methodString = ms[i].getReturnType().getName()+" "+ms[i].getDeclaringClass().getName()+"."+ - ms[i].getName()+"("+stringify(ms[i].getParameterTypes())+")"+ - (isBridge(ms[i])?" [BridgeMethod]":""); + for (java.lang.reflect.Method m : ms) { + String methodString = m.getReturnType().getName() + " " + m.getDeclaringClass().getName() + "." + + m.getName() + "(" + stringify(m.getParameterTypes()) + ")" + + (isBridge(m) ? " [BridgeMethod]" : ""); methodsFound.add(methodString); debugString.append("\n[").append(methodString).append("]"); } @@ -901,10 +901,9 @@ public class GenericsTests extends XMLBasedAjcTestCase { } // check the methods specified do exist - for (int i = 0; i < methods.length; i++) { - String string = methods[i]; + for (String string : methods) { if (!methodsFound.remove(string)) { - fail("Couldn't find ["+string+"] in the set of methods in "+classname+" => "+debugString); + fail("Couldn't find [" + string + "] in the set of methods in " + classname + " => " + debugString); } } StringBuffer unexpectedMethods = new StringBuffer(); @@ -953,9 +952,8 @@ public class GenericsTests extends XMLBasedAjcTestCase { JavaClass clazz = getClass(ajc,classname); Signature sigAttr = null; Attribute[] attrs = clazz.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; - if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute; + for (Attribute attribute : attrs) { + if (attribute.getName().equals("Signature")) sigAttr = (Signature) attribute; } return sigAttr; } @@ -965,11 +963,10 @@ public class GenericsTests extends XMLBasedAjcTestCase { Attribute[] attrs = clazz.getAttributes(); int signatureCount = 0; StringBuffer sb = new StringBuffer(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals("Signature")) { signatureCount++; - sb.append("\n"+((Signature)attribute).getSignature()); + sb.append("\n" + ((Signature) attribute).getSignature()); } } if (signatureCount>1) fail("Should be only one signature attribute but found "+signatureCount+sb.toString()); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc152/SynchronizationTransformTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc152/SynchronizationTransformTests.java index 92d2addfd..f03ebe3f0 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc152/SynchronizationTransformTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc152/SynchronizationTransformTests.java @@ -209,8 +209,7 @@ public class SynchronizationTransformTests extends XMLBasedAjcTestCase { protected Method getMethod(JavaClass cl, String methodname) { Method[] methods = cl.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method m = methods[i]; + for (Method m : methods) { if (m.getName().equals(methodname)) { return m; } @@ -258,8 +257,7 @@ public class SynchronizationTransformTests extends XMLBasedAjcTestCase { private String stringify(List<String> l) { StringBuffer result = new StringBuffer(); - for (Iterator<String> iter = l.iterator(); iter.hasNext();) { - String str = iter.next(); + for (String str : l) { result.append(str); result.append("\n"); } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc153/JDTLikeHandleProviderTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc153/JDTLikeHandleProviderTests.java index 2d398f86f..5e9e5b25e 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc153/JDTLikeHandleProviderTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc153/JDTLikeHandleProviderTests.java @@ -159,8 +159,8 @@ public class JDTLikeHandleProviderTests extends XMLBasedAjcTestCase { List children = parent.getChildren(); String handle1 = null; String handle2 = null; - for (Iterator iter = children.iterator(); iter.hasNext();) { - IProgramElement element = (IProgramElement) iter.next(); + for (Object child : children) { + IProgramElement element = (IProgramElement) child; if (element.getKind().equals(IProgramElement.Kind.ADVICE)) { if (handle1 == null) { handle1 = element.getHandleIdentifier(); @@ -408,8 +408,8 @@ public class JDTLikeHandleProviderTests extends XMLBasedAjcTestCase { List children = parent.getChildren(); String handle1 = null; String handle2 = null; - for (Iterator iter = children.iterator(); iter.hasNext();) { - IProgramElement element = (IProgramElement) iter.next(); + for (Object child : children) { + IProgramElement element = (IProgramElement) child; if (element.getKind().equals(IProgramElement.Kind.INITIALIZER)) { if (handle1 == null) { handle1 = element.getHandleIdentifier(); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc154/CustomMungerExtensionTest.java b/tests/src/test/java/org/aspectj/systemtest/ajc154/CustomMungerExtensionTest.java index 7c0d26d4c..6b1b8821c 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc154/CustomMungerExtensionTest.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc154/CustomMungerExtensionTest.java @@ -58,13 +58,13 @@ public class CustomMungerExtensionTest extends AjdeInteractionTestbed { CustomMungerFactory factory = (CustomMungerFactory) compiler.getCustomMungerFactory(); assertTrue(factory.getAllCreatedCustomShadowMungers().size() > 0); - for (Iterator<ShadowMunger> i = factory.getAllCreatedCustomShadowMungers().iterator(); i.hasNext();) { - assertTrue(((DumbShadowMunger) i.next()).called); + for (ShadowMunger shadowMunger : factory.getAllCreatedCustomShadowMungers()) { + assertTrue(((DumbShadowMunger) shadowMunger).called); } assertTrue(factory.getAllCreatedCustomTypeMungers().size() > 0); - for (Iterator<ConcreteTypeMunger> i = factory.getAllCreatedCustomTypeMungers().iterator(); i.hasNext();) { - assertTrue(((DumbTypeMunger) i.next()).called); + for (ConcreteTypeMunger concreteTypeMunger : factory.getAllCreatedCustomTypeMungers()) { + assertTrue(((DumbTypeMunger) concreteTypeMunger).called); } } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc160/SanityTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc160/SanityTests.java index 9bdb68665..41fb83bf2 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc160/SanityTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc160/SanityTests.java @@ -97,8 +97,7 @@ public class SanityTests extends org.aspectj.testing.XMLBasedAjcTestCase { toIgnore = "_" + (toIgnore == null ? "" : toIgnore) + "_"; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname); Method[] methods = jc.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { if (toIgnore.contains("_" + method.getName() + "_")) { continue; } @@ -113,8 +112,7 @@ public class SanityTests extends org.aspectj.testing.XMLBasedAjcTestCase { if (attrs == null) { return false; } - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals(attributeName)) { return true; } @@ -122,8 +120,7 @@ public class SanityTests extends org.aspectj.testing.XMLBasedAjcTestCase { if (attribute.getName().equals("Code")) { Code c = (Code) attribute; Attribute[] codeAttributes = c.getAttributes(); - for (int j = 0; j < codeAttributes.length; j++) { - Attribute codeAttribute = codeAttributes[j]; + for (Attribute codeAttribute : codeAttributes) { if (codeAttribute.getName().equals(attributeName)) { return true; // System.out.println(codeAttribute.getName()); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc161/Ajc161Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc161/Ajc161Tests.java index bcf640f3f..bba565a3a 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc161/Ajc161Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc161/Ajc161Tests.java @@ -141,8 +141,8 @@ public class Ajc161Tests extends org.aspectj.testing.XMLBasedAjcTestCase { Set entries = irm.getEntries(); boolean gotSomethingValid = false; String expected = "<recursivepackage{RecursiveCatcher.java'RecursiveCatcher~recursiveCall~I?method-call(void recursivepackage.RecursiveCatcher.recursiveCall(int))"; - for (Iterator iterator = entries.iterator(); iterator.hasNext();) { - String str = (String) iterator.next(); + for (Object entry : entries) { + String str = (String) entry; if (str.indexOf(expected) != -1) { gotSomethingValid = true; } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc1610/NewFeatures.java b/tests/src/test/java/org/aspectj/systemtest/ajc1610/NewFeatures.java index 34b72996f..cfed5a765 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc1610/NewFeatures.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc1610/NewFeatures.java @@ -127,9 +127,9 @@ public class NewFeatures extends org.aspectj.testing.XMLBasedAjcTestCase { private Method getPreClinitMethod(JavaClass myClass) { Method lm[] = myClass.getMethods(); - for (int i = 0; i < lm.length; i++) { - if (lm[i].getName().equals("ajc$preClinit")) { - return lm[i]; + for (Method method : lm) { + if (method.getName().equals("ajc$preClinit")) { + return method; } } return null; diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc1612/Ajc1612Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc1612/Ajc1612Tests.java index 9e857cb31..d9e52d2b1 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc1612/Ajc1612Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc1612/Ajc1612Tests.java @@ -256,8 +256,7 @@ public class Ajc1612Tests extends org.aspectj.testing.XMLBasedAjcTestCase { JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X"); Method[] meths = jc.getMethods(); boolean checked = false; - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (method.getName().equals("ajc$before$X$2$3444dde4")) { System.out.println(method.getName()); System.out.println(stringify(method.getLocalVariableTable())); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc163/Ajc163Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc163/Ajc163Tests.java index c0bd95645..48d120761 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc163/Ajc163Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc163/Ajc163Tests.java @@ -246,9 +246,9 @@ public class Ajc163Tests extends org.aspectj.testing.XMLBasedAjcTestCase { JavaClass jc = Utils.getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(), "Test"); Method[] ms = jc.getMethods(); Method m = null; - for (int i = 0; i < ms.length; i++) { - if (ms[i].getName().equals("sayHello")) { - m = ms[i]; + for (Method method : ms) { + if (method.getName().equals("sayHello")) { + m = method; } } if (m.getLocalVariableTable() == null) { @@ -310,8 +310,7 @@ public class Ajc163Tests extends org.aspectj.testing.XMLBasedAjcTestCase { private void print(LocalVariableTable localVariableTable) { LocalVariable[] lvs = localVariableTable.getLocalVariableTable(); - for (int i = 0; i < lvs.length; i++) { - LocalVariable localVariable = lvs[i]; + for (LocalVariable localVariable : lvs) { System.out.println(localVariable); } } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc164/Ajc164Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc164/Ajc164Tests.java index f474af49c..1b1181535 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc164/Ajc164Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc164/Ajc164Tests.java @@ -427,8 +427,7 @@ public class Ajc164Tests extends org.aspectj.testing.XMLBasedAjcTestCase { return whereToLook; } List<IProgramElement> kids = whereToLook.getChildren(); - for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) { - IProgramElement object = iterator.next(); + for (IProgramElement object : kids) { if (object.getSourceLocation() != null && object.getSourceLocation().getLine() == line) { return object; } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc165/Ajc165Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc165/Ajc165Tests.java index 6b8923e2a..762865c57 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc165/Ajc165Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc165/Ajc165Tests.java @@ -85,8 +85,8 @@ public class Ajc165Tests extends org.aspectj.testing.XMLBasedAjcTestCase { List<IMessage> ms = ajc.getLastCompilationResult().getWarningMessages(); boolean checked = true; // Look for the message relating to 'List' and check the offsets - for (int i = 0; i < ms.size(); i++) { - LintMessage m = (LintMessage) ms.get(i); + for (IMessage iMessage : ms) { + LintMessage m = (LintMessage) iMessage; if (m.toString().indexOf("List") != -1) { // 225/228 on windows - 237/240 on linux if (!(m.getSourceStart() == 225 || m.getSourceStart() == 237)) { diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc173/Ajc173Tests.java b/tests/src/test/java/org/aspectj/systemtest/ajc173/Ajc173Tests.java index 98d16daae..12fdfd8be 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc173/Ajc173Tests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc173/Ajc173Tests.java @@ -61,8 +61,8 @@ public class Ajc173Tests extends org.aspectj.testing.XMLBasedAjcTestCase { Method m = getMethodStartsWith(jc, "getName"); assertNotNull(m); AnnotationGen[] ags = m.getAnnotations(); - for (int i=0;i<ags.length;i++) { - System.out.println(ags[i]); + for (AnnotationGen ag : ags) { + System.out.println(ag); } assertEquals(1,ags.length); assertEquals("LFoo;",ags[0].getTypeSignature()); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc190/Annotations.java b/tests/src/test/java/org/aspectj/systemtest/ajc190/Annotations.java index 971e53435..557dd0743 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc190/Annotations.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc190/Annotations.java @@ -53,8 +53,7 @@ public class Annotations extends XMLBasedAjcTestCase { JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Program"); Method[] meths = jc.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (method.getName().equals("m1")) { assertTrue("Didn't have annotations - were they lost? method=" + method.getName(), method.getAnnotations().length == 1); diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc190/EfficientTJPTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc190/EfficientTJPTests.java index 0bef8e7db..2f01d0d97 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc190/EfficientTJPTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc190/EfficientTJPTests.java @@ -107,11 +107,10 @@ public class EfficientTJPTests extends XMLBasedAjcTestCase { try { JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname); Method[] meths = jc.getMethods(); - for (int i = 0; i < meths.length; i++) { - Method method = meths[i]; + for (Method method : meths) { if (method.getName().equals("ajc$preClinit")) { String code = method.getCode().getCodeString(); - assertTrue("Expected to contain '"+text+"':\n"+code,code.contains(text)); + assertTrue("Expected to contain '" + text + "':\n" + code, code.contains(text)); return; } } diff --git a/tests/src/test/java/org/aspectj/systemtest/ajc190/ModuleTests.java b/tests/src/test/java/org/aspectj/systemtest/ajc190/ModuleTests.java index ac5eb14e4..5937c4423 100644 --- a/tests/src/test/java/org/aspectj/systemtest/ajc190/ModuleTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/ajc190/ModuleTests.java @@ -112,8 +112,7 @@ public class ModuleTests extends XMLBasedAjcTestCaseForJava9OrLater { toIgnore = "_" + (toIgnore == null ? "" : toIgnore) + "_"; JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname); Method[] methods = jc.getMethods(); - for (int i = 0; i < methods.length; i++) { - Method method = methods[i]; + for (Method method : methods) { if (toIgnore.contains("_" + method.getName() + "_")) { continue; } @@ -128,8 +127,7 @@ public class ModuleTests extends XMLBasedAjcTestCaseForJava9OrLater { if (attrs == null) { return false; } - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals(attributeName)) { return true; } @@ -137,8 +135,7 @@ public class ModuleTests extends XMLBasedAjcTestCaseForJava9OrLater { if (attribute.getName().equals("Code")) { Code c = (Code) attribute; Attribute[] codeAttributes = c.getAttributes(); - for (int j = 0; j < codeAttributes.length; j++) { - Attribute codeAttribute = codeAttributes[j]; + for (Attribute codeAttribute : codeAttributes) { if (codeAttribute.getName().equals(attributeName)) { return true; // System.out.println(codeAttribute.getName()); diff --git a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AbstractMultiProjectIncrementalAjdeInteractionTestbed.java b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AbstractMultiProjectIncrementalAjdeInteractionTestbed.java index 229a22a5d..916801690 100644 --- a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AbstractMultiProjectIncrementalAjdeInteractionTestbed.java +++ b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AbstractMultiProjectIncrementalAjdeInteractionTestbed.java @@ -65,8 +65,8 @@ public class AbstractMultiProjectIncrementalAjdeInteractionTestbed extends AjdeI // System.out.println("kvp: " + object + " = " + m.get(object)); // } // } - for (Iterator<IProgramElement> i = node.getChildren().iterator(); i.hasNext();) { - dumptree( i.next(), indent + 2); + for (IProgramElement iProgramElement : node.getChildren()) { + dumptree(iProgramElement, indent + 2); } } } @@ -113,11 +113,10 @@ public class AbstractMultiProjectIncrementalAjdeInteractionTestbed extends AjdeI IRelationshipMap relmap = getModelFor(project).getRelationshipMap(); int ctr = 0; Set<String> entries = relmap.getEntries(); - for (Iterator<String> iter = entries.iterator(); iter.hasNext();) { - String hid = (String) iter.next(); + for (String hid : entries) { List<IRelationship> rels = relmap.get(hid); - for (Iterator<IRelationship> iterator = rels.iterator(); iterator.hasNext();) { - ctr+=iterator.next().getTargets().size(); + for (IRelationship rel : rels) { + ctr += rel.getTargets().size(); } } return ctr; @@ -152,8 +151,7 @@ public class AbstractMultiProjectIncrementalAjdeInteractionTestbed extends AjdeI String contents[] = location.list(); if (contents == null) return; - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(location, string); if (f.isDirectory()) { collectUpFiles(f, base, collectionPoint); @@ -206,8 +204,7 @@ public class AbstractMultiProjectIncrementalAjdeInteractionTestbed extends AjdeI String contents[] = from.list(); if (contents == null) return; - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(from, string); File t = new File(to, string); diff --git a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java index 0fe276f46..9c5770ef8 100644 --- a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java +++ b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/AjdeInteractionTestbed.java @@ -244,13 +244,13 @@ public class AjdeInteractionTestbed extends TestCase { List<String> filesForCompilation = new ArrayList<String>(); collectUpFiles(projectBase, projectBase, filesForCompilation); boolean changed = false; - for (int i = 0; i < filesForCompilation.size(); i++) { - if (!currentFiles.contains(filesForCompilation.get(i))) { + for (String s : filesForCompilation) { + if (!currentFiles.contains(s)) { changed = true; } } - for (int i = 0; i < currentFiles.size(); i++) { - if (!filesForCompilation.contains(currentFiles.get(i))) { + for (String currentFile : currentFiles) { + if (!filesForCompilation.contains(currentFile)) { changed = true; } } @@ -266,13 +266,13 @@ public class AjdeInteractionTestbed extends TestCase { List<String> collector = new ArrayList<String>(); collectUpXmlFiles(projectBase, projectBase, collector); boolean changed = false; - for (int i = 0; i < collector.size(); i++) { - if (!currentXmlFiles.contains(collector.get(i))) { + for (String s : collector) { + if (!currentXmlFiles.contains(s)) { changed = true; } } - for (int i = 0; i < currentXmlFiles.size(); i++) { - if (!collector.contains(currentXmlFiles.get(i))) { + for (String currentXmlFile : currentXmlFiles) { + if (!collector.contains(currentXmlFile)) { changed = true; } } @@ -286,8 +286,7 @@ public class AjdeInteractionTestbed extends TestCase { if (contents == null) { return; } - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(location, string); if (f.isDirectory()) { collectUpFiles(f, base, collectionPoint); @@ -311,8 +310,7 @@ public class AjdeInteractionTestbed extends TestCase { if (contents == null) { return; } - for (int i = 0; i < contents.length; i++) { - String string = contents[i]; + for (String string : contents) { File f = new File(location, string); if (f.isDirectory()) { collectUpXmlFiles(f, base, collectionPoint); @@ -365,8 +363,7 @@ public class AjdeInteractionTestbed extends TestCase { public void checkForError(String projectName, String anError) { AjCompiler compiler = CompilerFactory.getCompilerForProjectWithDir(sandboxDir + File.separator + projectName); List<IMessage> messages = ((MultiProjTestMessageHandler) compiler.getMessageHandler()).getErrorMessages(); - for (Iterator<IMessage> iter = messages.iterator(); iter.hasNext();) { - IMessage element = iter.next(); + for (IMessage element : messages) { if (element.getMessage().indexOf(anError) != -1) { return; } @@ -409,13 +406,13 @@ public class AjdeInteractionTestbed extends TestCase { System.out.println("Build took: " + getTimeTakenForBuild(projectName) + "ms"); List<String> compiled = getCompiledFiles(projectName); System.out.println("Compiled: " + compiled.size() + " files"); - for (Iterator<String> iter = compiled.iterator(); iter.hasNext();) { - System.out.println(" :" + iter.next()); + for (String value : compiled) { + System.out.println(" :" + value); } List<String> woven = getWovenClasses(projectName); System.out.println("Wove: " + woven.size() + " files"); - for (Iterator<String> iter = woven.iterator(); iter.hasNext();) { - System.out.println(" :" + iter.next()); + for (String s : woven) { + System.out.println(" :" + s); } if (wasFullBuild()) { System.out.println("It was a batch (full) build"); diff --git a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MoreOutputLocationManagerTests.java b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MoreOutputLocationManagerTests.java index c35b88610..538d2dcbd 100644 --- a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MoreOutputLocationManagerTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MoreOutputLocationManagerTests.java @@ -68,8 +68,7 @@ public class MoreOutputLocationManagerTests extends AbstractMultiProjectIncremen Map<String,File> classNameToFileMap = state.getClassNameToFileMap(); assertFalse("expected there to be classes ", classNameToFileMap.isEmpty()); Set<Map.Entry<String,File>> entrySet = classNameToFileMap.entrySet(); - for (Iterator<Map.Entry<String,File>> iterator = entrySet.iterator(); iterator.hasNext();) { - Map.Entry<String,File> entry = iterator.next(); + for (Map.Entry<String, File> entry : entrySet) { String className = entry.getKey(); String fullClassName = expectedOutputDir + File.separator + className.replace('.', File.separatorChar) + ".class"; File file = entry.getValue(); diff --git a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java index 0d01d9634..75600dded 100644 --- a/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java +++ b/tests/src/test/java/org/aspectj/systemtest/incremental/tools/MultiProjectIncrementalTests.java @@ -921,8 +921,7 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa checkWasFullBuild(); List<IMessage> weaveMessages = getWeavingMessages(p); if (weaveMessages.size() != 1) { - for (Iterator<IMessage> iterator = weaveMessages.iterator(); iterator.hasNext();) { - Object object = iterator.next(); + for (Object object : weaveMessages) { System.out.println(object); } fail("Expected just one weave message. The aop.xml should have limited the weaving"); @@ -939,8 +938,7 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa assertNotNull(ps); assertEquals(2, ps.size()); int count = 0; - for (Iterator<String> iterator = ps.iterator(); iterator.hasNext();) { - String type = iterator.next(); + for (String type : ps) { if (type.equals("java.io.Serializable")) { count++; } @@ -997,14 +995,13 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa IRelationshipMap asmRelMap = getModelFor("P4").getRelationshipMap(); assertEquals("There should be two relationships in the relationship map", 2, asmRelMap.getEntries().size()); - for (Iterator<String> iter = asmRelMap.getEntries().iterator(); iter.hasNext();) { - String sourceOfRelationship = (String) iter.next(); + for (String sourceOfRelationship : asmRelMap.getEntries()) { IProgramElement ipe = getModelFor("P4").getHierarchy().findElementForHandle(sourceOfRelationship); assertNotNull("expected to find IProgramElement with handle " + sourceOfRelationship + " but didn't", ipe); - if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { + if (ipe.getKind().equals(Kind.ADVICE)) { assertEquals("expected source of relationship to be " + advice.toString() + " but found " + ipe.toString(), advice, ipe); - } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { + } else if (ipe.getKind().equals(Kind.CODE)) { assertEquals( "expected source of relationship to be " + codeElement.toString() + " but found " + ipe.toString(), codeElement, ipe); @@ -1014,17 +1011,16 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa } List<IRelationship> relationships = asmRelMap.get(ipe); assertNotNull("expected " + ipe.getName() + " to have some " + "relationships", relationships); - for (Iterator<IRelationship> iterator = relationships.iterator(); iterator.hasNext();) { - Relationship rel = (Relationship) iterator.next(); + for (IRelationship relationship : relationships) { + Relationship rel = (Relationship) relationship; List<String> targets = rel.getTargets(); - for (Iterator<String> iterator2 = targets.iterator(); iterator2.hasNext();) { - String t = (String) iterator2.next(); + for (String t : targets) { IProgramElement link = getModelFor("P4").getHierarchy().findElementForHandle(t); - if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) { + if (ipe.getKind().equals(Kind.ADVICE)) { assertEquals( "expected target of relationship to be " + codeElement.toString() + " but found " + link.toString(), codeElement, link); - } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) { + } else if (ipe.getKind().equals(Kind.CODE)) { assertEquals( "expected target of relationship to be " + advice.toString() + " but found " + link.toString(), advice, link); @@ -1102,21 +1098,18 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa IProgramElement root = model.getHierarchy().getRoot(); ProgramElement theITD = (ProgramElement) findElementAtLine(root, 7); Map<String, Object> m = theITD.kvpairs; - for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) { - String type = iterator.next(); + for (String type : m.keySet()) { System.out.println(type + " = " + m.get(type)); } // return type of the ITD assertEquals("a.b.c.B", theITD.getCorrespondingType(true)); List<char[]> ptypes = theITD.getParameterTypes(); - for (Iterator<char[]> iterator = ptypes.iterator(); iterator.hasNext();) { - char[] object = iterator.next(); + for (char[] object : ptypes) { System.out.println("p = " + new String(object)); } ProgramElement decp = (ProgramElement) findElementAtLine(root, 8); m = decp.kvpairs; - for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) { - String type = iterator.next(); + for (String type : m.keySet()) { System.out.println(type + " = " + m.get(type)); } List<String> l = decp.getParentTypes(); @@ -1723,8 +1716,8 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa } List<IProgramElement> kids = start.getChildren(); if (kids != null) { - for (int i = 0; i < kids.size(); i++) { - IProgramElement found = getChild((IProgramElement) kids.get(i), name); + for (IProgramElement kid : kids) { + IProgramElement found = getChild((IProgramElement) kid, name); if (found != null) { return found; } @@ -3939,8 +3932,7 @@ public class MultiProjectIncrementalTests extends AbstractMultiProjectIncrementa if (rels == null) { fail("Did not find any related elements!"); } - for (Iterator<IRelationship> iter = rels.iterator(); iter.hasNext();) { - IRelationship element = iter.next(); + for (IRelationship element : rels) { List<String> targets = element.getTargets(); if (output == null) { output = new ArrayList<String>(); diff --git a/tests/src/test/java/org/aspectj/systemtest/model/ModelTestCase.java b/tests/src/test/java/org/aspectj/systemtest/model/ModelTestCase.java index 0e443c3d3..b2c3ca6c9 100644 --- a/tests/src/test/java/org/aspectj/systemtest/model/ModelTestCase.java +++ b/tests/src/test/java/org/aspectj/systemtest/model/ModelTestCase.java @@ -168,8 +168,7 @@ public abstract class ModelTestCase extends XMLBasedAjcTestCase { } // iterate over what we found - for (Iterator<String> iter = foundFileContents.iterator(); iter.hasNext();) { - String line = (String) iter.next(); + for (String line : foundFileContents) { if (debugTest) System.err.println("looking at model entry: " + line); if (!fileContents.contains(line)) { @@ -177,8 +176,7 @@ public abstract class ModelTestCase extends XMLBasedAjcTestCase { if (debugTest) { System.err.println("couldn't find: " + line); - for (Iterator<String> iterator = fileContents.iterator(); iterator.hasNext();) { - String element = (String) iterator.next(); + for (String element : fileContents) { System.err.println("compared with: " + element); } } @@ -192,8 +190,7 @@ public abstract class ModelTestCase extends XMLBasedAjcTestCase { } if (debugTest && !fileContents.isEmpty()) { - for (Iterator<String> iter = fileContents.iterator(); iter.hasNext();) { - String element = (String) iter.next(); + for (String element : fileContents) { System.err.println("remaining: " + element); } } diff --git a/util/src/main/java/org/aspectj/util/FileUtil.java b/util/src/main/java/org/aspectj/util/FileUtil.java index fef580e83..6e55742b1 100644 --- a/util/src/main/java/org/aspectj/util/FileUtil.java +++ b/util/src/main/java/org/aspectj/util/FileUtil.java @@ -147,12 +147,11 @@ public class FileUtil { return 0; } - for (Iterator<String> iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) { - String suffix = iter.next(); - if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) { - return suffix.length(); - } - } + for (String suffix : SOURCE_SUFFIXES) { + if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) { + return suffix.length(); + } + } return 0; } @@ -335,18 +334,18 @@ public class FileUtil { } StringBuffer result = new StringBuffer(); boolean first = true; - for (int i = 0; i < paths.length; i++) { - String path = paths[i]; - if (null == path) { - continue; - } - if (first) { - first = false; - } else { - result.append(infix); - } - result.append(path); - } + for (String path : paths) { + if (null == path) { + continue; + } + if (first) { + first = false; + } + else { + result.append(infix); + } + result.append(path); + } return result.toString(); } @@ -540,24 +539,24 @@ public class FileUtil { return 0; } int result = 0; - for (int i = 0; i < fromFiles.length; i++) { - String string = fromFiles[i]; - File file = new File(dir, string); - if ((null == filter) || filter.accept(file)) { - if (file.isDirectory()) { - result += deleteContents(file, filter, deleteEmptyDirs); - String[] fileContent = file.list(); - if (deleteEmptyDirs && fileContent != null - && 0 == fileContent.length) { - file.delete(); - } - } else { - /* boolean ret = */ - file.delete(); - result++; - } - } - } + for (String string : fromFiles) { + File file = new File(dir, string); + if ((null == filter) || filter.accept(file)) { + if (file.isDirectory()) { + result += deleteContents(file, filter, deleteEmptyDirs); + String[] fileContent = file.list(); + if (deleteEmptyDirs && fileContent != null + && 0 == fileContent.length) { + file.delete(); + } + } + else { + /* boolean ret = */ + file.delete(); + result++; + } + } + } return result; } @@ -752,15 +751,14 @@ public class FileUtil { File[] result = null; if (!LangUtil.isEmpty(suffixes)) { ArrayList<File> list = new ArrayList<File>(); - for (int i = 0; i < paths.length; i++) { - String path = paths[i]; - for (int j = 0; j < suffixes.length; j++) { - if (path.endsWith(suffixes[j])) { - list.add(new File(basedir, paths[i])); - break; - } - } - } + for (String path : paths) { + for (String suffix : suffixes) { + if (path.endsWith(suffix)) { + list.add(new File(basedir, path)); + break; + } + } + } result = list.toArray(new File[0]); } else { result = new File[paths.length]; @@ -1080,9 +1078,9 @@ public class FileUtil { public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) { - s.writeBoolean(a[i]); - } + for (boolean b : a) { + s.writeBoolean(b); + } } /** @@ -1103,9 +1101,9 @@ public class FileUtil { public static void writeIntArray(int[] a, DataOutputStream s) throws IOException { int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) { - s.writeInt(a[i]); - } + for (int j : a) { + s.writeInt(j); + } } /** @@ -1130,9 +1128,9 @@ public class FileUtil { } int len = a.length; s.writeInt(len); - for (int i = 0; i < len; i++) { - s.writeUTF(a[i]); - } + for (String value : a) { + s.writeUTF(value); + } } /** @@ -1276,13 +1274,12 @@ public class FileUtil { return Collections.emptyList(); } ArrayList<String> result = new ArrayList<String>(); - for (Iterator<String> iter = sources.iterator(); iter.hasNext();) { - String path = iter.next(); - String error = lineSeek(sought, path, listAll, result); - if ((null != error) && (null != errorSink)) { - errorSink.println(error); - } - } + for (String path : sources) { + String error = lineSeek(sought, path, listAll, result); + if ((null != error) && (null != errorSink)) { + errorSink.println(error); + } + } return result; } @@ -1357,53 +1354,52 @@ public class FileUtil { return true; } long delayUntil = System.currentTimeMillis(); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if ((null == file) || !file.exists()) { - continue; - } - long nextModTime = file.lastModified(); - if (nextModTime > delayUntil) { - delayUntil = nextModTime; - } - } + for (File file : files) { + if ((null == file) || !file.exists()) { + continue; + } + long nextModTime = file.lastModified(); + if (nextModTime > delayUntil) { + delayUntil = nextModTime; + } + } return LangUtil.sleepUntil(++delayUntil); } private static void listClassFiles(final File baseDir, ArrayList<File> result) { File[] files = baseDir.listFiles(); - for (int i = 0; i < files.length; i++) { - File f = files[i]; - if (f.isDirectory()) { - listClassFiles(f, result); - } else { - if (f.getName().endsWith(".class")) { - result.add(f); - } - } - } + for (File f : files) { + if (f.isDirectory()) { + listClassFiles(f, result); + } + else { + if (f.getName().endsWith(".class")) { + result.add(f); + } + } + } } private static void listFiles(final File baseDir, ArrayList<File> result, FileFilter filter) { File[] files = baseDir.listFiles(); // hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650 final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter)); - for (int i = 0; i < files.length; i++) { - File f = files[i]; - if (f.isDirectory()) { - if (skipCVS) { - String name = f.getName().toLowerCase(); - if ("cvs".equals(name) || "sccs".equals(name)) { - continue; - } - } - listFiles(f, result, filter); - } else { - if (filter.accept(f)) { - result.add(f); - } - } - } + for (File f : files) { + if (f.isDirectory()) { + if (skipCVS) { + String name = f.getName().toLowerCase(); + if ("cvs".equals(name) || "sccs".equals(name)) { + continue; + } + } + listFiles(f, result, filter); + } + else { + if (filter.accept(f)) { + result.add(f); + } + } + } } /** @return true if input is not null and contains no path separator */ @@ -1415,15 +1411,16 @@ public class FileUtil { final String dirPrefix = (null == dir ? "" : dir + "/"); final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir)); final String[] files = dirFile.list(); - for (int i = 0; i < files.length; i++) { - File f = new File(dirFile, files[i]); - String path = dirPrefix + files[i]; - if (f.isDirectory()) { - listFiles(baseDir, path, result); - } else { - result.add(path); - } - } + for (String file : files) { + File f = new File(dirFile, file); + String path = dirPrefix + file; + if (f.isDirectory()) { + listFiles(baseDir, path, result); + } + else { + result.add(path); + } + } } private FileUtil() { @@ -1432,9 +1429,9 @@ public class FileUtil { public static List<String> makeClasspath(URL[] urls) { List<String> ret = new LinkedList<String>(); if (urls != null) { - for (int i = 0; i < urls.length; i++) { - ret.add(toPathString(urls[i])); - } + for (URL url : urls) { + ret.add(toPathString(url)); + } } return ret; } diff --git a/util/src/main/java/org/aspectj/util/GenericSignature.java b/util/src/main/java/org/aspectj/util/GenericSignature.java index bfefc007e..5fa7ac632 100644 --- a/util/src/main/java/org/aspectj/util/GenericSignature.java +++ b/util/src/main/java/org/aspectj/util/GenericSignature.java @@ -30,8 +30,8 @@ public class GenericSignature { StringBuffer ret = new StringBuffer(); ret.append(formalTypeParameters.toString()); ret.append(superclassSignature.toString()); - for (int i = 0; i < superInterfaceSignatures.length; i++) { - ret.append(superInterfaceSignatures[i].toString()); + for (ClassTypeSignature superInterfaceSignature : superInterfaceSignatures) { + ret.append(superInterfaceSignature.toString()); } return ret.toString(); } @@ -55,20 +55,20 @@ public class GenericSignature { StringBuffer sb = new StringBuffer(); if (formalTypeParameters.length > 0) { sb.append("<"); - for (int i = 0; i < formalTypeParameters.length; i++) { - sb.append(formalTypeParameters[i].toString()); + for (FormalTypeParameter formalTypeParameter : formalTypeParameters) { + sb.append(formalTypeParameter.toString()); } sb.append(">"); } sb.append("("); - for (int i = 0; i < parameters.length; i++) { - sb.append(parameters[i].toString()); + for (TypeSignature parameter : parameters) { + sb.append(parameter.toString()); } sb.append(")"); sb.append(returnType.toString()); - for (int i = 0; i < throwsSignatures.length; i++) { + for (FieldTypeSignature throwsSignature : throwsSignatures) { sb.append("^"); - sb.append(throwsSignatures[i].toString()); + sb.append(throwsSignature.toString()); } return sb.toString(); } @@ -89,9 +89,9 @@ public class GenericSignature { ret.append(identifier); ret.append(":"); ret.append(classBound.toString()); - for (int i = 0; i < interfaceBounds.length; i++) { + for (FieldTypeSignature interfaceBound : interfaceBounds) { ret.append(":"); - ret.append(interfaceBounds[i].toString()); + ret.append(interfaceBound.toString()); } return ret.toString(); } @@ -212,8 +212,8 @@ public class GenericSignature { sb.append(identifier); if (typeArguments.length > 0) { sb.append("<"); - for (int i = 0; i < typeArguments.length; i++) { - sb.append(typeArguments[i].toString()); + for (TypeArgument typeArgument : typeArguments) { + sb.append(typeArgument.toString()); } sb.append(">"); } diff --git a/util/src/main/java/org/aspectj/util/GenericSignatureParser.java b/util/src/main/java/org/aspectj/util/GenericSignatureParser.java index 28c8db83d..27670cc00 100644 --- a/util/src/main/java/org/aspectj/util/GenericSignatureParser.java +++ b/util/src/main/java/org/aspectj/util/GenericSignatureParser.java @@ -194,8 +194,8 @@ public class GenericSignatureParser { } else if (tokenStream[tokenIndex].equals("<")) { ret.append("<"); TypeArgument[] tArgs = maybeParseTypeArguments(); - for (int i = 0; i < tArgs.length; i++) { - ret.append(tArgs[i].toString()); + for (TypeArgument tArg : tArgs) { + ret.append(tArg.toString()); } ret.append(">"); outerType = new SimpleClassTypeSignature(identifier, tArgs); diff --git a/util/src/main/java/org/aspectj/util/PartialOrder.java b/util/src/main/java/org/aspectj/util/PartialOrder.java index 8bb9f3b77..14f23b0d6 100644 --- a/util/src/main/java/org/aspectj/util/PartialOrder.java +++ b/util/src/main/java/org/aspectj/util/PartialOrder.java @@ -88,8 +88,7 @@ public class PartialOrder { private static <T extends PartialComparable> void addNewPartialComparable(List<SortObject<T>> graph, T o) { SortObject<T> so = new SortObject<T>(o); - for (Iterator<SortObject<T>> i = graph.iterator(); i.hasNext();) { - SortObject<T> other = i.next(); + for (SortObject<T> other : graph) { so.addDirectedLinks(other); } graph.add(so); @@ -125,8 +124,8 @@ public class PartialOrder { // ??? I don't like creating this data structure, but it does give good // ??? separation of concerns. List<SortObject<T>> sortList = new LinkedList<SortObject<T>>(); - for (Iterator<T> i = objects.iterator(); i.hasNext();) { - addNewPartialComparable(sortList, i.next()); + for (T object : objects) { + addNewPartialComparable(sortList, object); } // System.out.println(sortList); diff --git a/util/src/main/java/org/aspectj/util/Reflection.java b/util/src/main/java/org/aspectj/util/Reflection.java index 3650962cc..d78f67101 100644 --- a/util/src/main/java/org/aspectj/util/Reflection.java +++ b/util/src/main/java/org/aspectj/util/Reflection.java @@ -57,8 +57,7 @@ public class Reflection { public static Method getMatchingMethod(Class<?> class_, String name, Object[] args) { Method[] meths = class_.getMethods(); - for (int i=0; i < meths.length; i++) { - Method meth = meths[i]; + for (Method meth : meths) { if (meth.getName().equals(name) && isCompatible(meth, args)) { return meth; } @@ -101,25 +100,24 @@ public class Reflection { ArrayList<File> libs = new ArrayList<File>(); ArrayList<URL> urls = new ArrayList<URL>(); String[] entries = LangUtil.splitClasspath(classpath); - for (int i = 0; i < entries.length; i++) { - String entry = entries[i]; - URL url = makeURL(entry); - if (null != url) { - urls.add(url); - } - File file = new File(entries[i]); + for (String entry : entries) { + URL url = makeURL(entry); + if (null != url) { + urls.add(url); + } + File file = new File(entry); // tolerate bad entries b/c bootclasspath sometimes has them // if (!file.canRead()) { // throw new IllegalArgumentException("cannot read " + file); // } - if (FileUtil.isZipFile(file)) { - libs.add(file); - } else if (file.isDirectory()) { - dirs.add(file); - } else { - // not URL, zip, or dir - unsure what to do - } - } + if (FileUtil.isZipFile(file)) { + libs.add(file); + } else if (file.isDirectory()) { + dirs.add(file); + } else { + // not URL, zip, or dir - unsure what to do + } + } File[] dirRa = (File[]) dirs.toArray(new File[0]); File[] libRa = (File[]) libs.toArray(new File[0]); URL[] urlRa = (URL[]) urls.toArray(new URL[0]); diff --git a/util/src/main/java/org/aspectj/util/UtilClassLoader.java b/util/src/main/java/org/aspectj/util/UtilClassLoader.java index 091e022a3..4704bfcc9 100644 --- a/util/src/main/java/org/aspectj/util/UtilClassLoader.java +++ b/util/src/main/java/org/aspectj/util/UtilClassLoader.java @@ -102,12 +102,12 @@ public class UtilClassLoader extends URLClassLoader { /** @return null if class not found or byte[] of class otherwise */ private byte[] readClass(String className) throws ClassNotFoundException { final String fileName = className.replace('.', '/')+".class"; - for (Iterator<File> iter = dirs.iterator(); iter.hasNext();) { - File file = new File(iter.next(), fileName); - if (file.canRead()) { - return getClassData(file); - } - } + for (File dir : dirs) { + File file = new File(dir, fileName); + if (file.canRead()) { + return getClassData(file); + } + } return null; } diff --git a/util/src/test/java/org/aspectj/util/FileUtilTest.java b/util/src/test/java/org/aspectj/util/FileUtilTest.java index 2d61a6a79..367c0ea5e 100644 --- a/util/src/test/java/org/aspectj/util/FileUtilTest.java +++ b/util/src/test/java/org/aspectj/util/FileUtilTest.java @@ -166,13 +166,13 @@ public class FileUtilTest extends TestCase { return; } File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - String path = files[i].getPath(); - if (!files[i].getName().startsWith(".")) { - if (files[i].isFile()) { + for (File file : files) { + String path = file.getPath(); + if (!file.getName().startsWith(".")) { + if (file.isFile()) { paths.add(path); - } else if (files[i].isDirectory()) { - doDirPaths(files[i], paths); + } else if (file.isDirectory()) { + doDirPaths(file, paths); } else { log("not file or dir: " + dir + "/" + path); } @@ -325,8 +325,8 @@ public class FileUtilTest extends TestCase { public void testGetURL() { String[] args = new String[] { ".", "../util/testdata", "../lib/test/aspectjrt.jar" }; - for (int i = 0; i < args.length; i++) { - checkGetURL(args[i]); + for (String arg : args) { + checkGetURL(arg); } } @@ -496,8 +496,8 @@ public class FileUtilTest extends TestCase { sb.append(LangUtil.EOL); } final String contents = sb.toString(); - for (int i = 0; i < sources.length; i++) { - File file = new File(sources[i]); + for (String source : sources) { + File file = new File(source); FileUtil.writeAsString(file, contents); tempFiles.add(file); } @@ -588,9 +588,9 @@ public class FileUtilTest extends TestCase { assertTrue(d.exists()); tempFiles.add(d); assertTrue(d.canWrite()); - for (int i = 0; i < filenames.length; i++) { - File f = new File(d, filenames[i]); - assertTrue(filenames[i], f.createNewFile()); + for (String filename : filenames) { + File f = new File(d, filename); + assertTrue(filename, f.createNewFile()); } return d; } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java b/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java index 08a261569..f49a1bb33 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/AtAjAttributes.java @@ -203,8 +203,7 @@ public class AtAjAttributes { boolean containsPointcut = false; boolean containsAnnotationClassReference = false; Constant[] cpool = javaClass.getConstantPool().getConstantPool(); - for (int i = 0; i < cpool.length; i++) { - Constant constant = cpool[i]; + for (Constant constant : cpool) { if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) { String constantValue = ((ConstantUtf8) constant).getValue(); if (constantValue.length() > 28 && constantValue.charAt(1) == PACKAGE_INITIAL_CHAR) { @@ -233,8 +232,7 @@ public class AtAjAttributes { boolean hasAtPrecedenceAnnotation = false; WeaverVersionInfo wvinfo = null; - for (int i = 0; i < attributes.length; i++) { - Attribute attribute = attributes[i]; + for (Attribute attribute : attributes) { if (acceptAttribute(attribute)) { RuntimeAnnos rvs = (RuntimeAnnos) attribute; // we don't need to look for several attribute occurrences since @@ -345,8 +343,7 @@ public class AtAjAttributes { AjAttributeMethodStruct mstruct = null; boolean processedPointcut = false; Attribute[] mattributes = method.getAttributes(); - for (int j = 0; j < mattributes.length; j++) { - Attribute mattribute = mattributes[j]; + for (Attribute mattribute : mattributes) { if (acceptAttribute(mattribute)) { // TODO speed all this nonsense up rather than looking // through all the annotations every time @@ -368,8 +365,7 @@ public class AtAjAttributes { // code style declare error / warning / implements / parents are field // attributes Field[] fs = javaClass.getFields(); - for (int i = 0; i < fs.length; i++) { - Field field = fs[i]; + for (Field field : fs) { if (field.getName().startsWith(NameMangler.PREFIX)) { continue; // already dealt with by ajc... } @@ -378,8 +374,7 @@ public class AtAjAttributes { AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler); Attribute[] fattributes = field.getAttributes(); - for (int j = 0; j < fattributes.length; j++) { - Attribute fattribute = fattributes[j]; + for (Attribute fattribute : fattributes) { if (acceptAttribute(fattribute)) { RuntimeAnnos frvs = (RuntimeAnnos) fattribute; if (handleDeclareErrorOrWarningAnnotation(model, frvs, fstruct) @@ -433,8 +428,7 @@ public class AtAjAttributes { // be too silent. boolean hasAtAspectJAnnotation = false; boolean hasAtAspectJAnnotationMustReturnVoid = false; - for (int i = 0; i < attributes.length; i++) { - Attribute attribute = attributes[i]; + for (Attribute attribute : attributes) { try { if (acceptAttribute(attribute)) { RuntimeAnnos rvs = (RuntimeAnnos) attribute; @@ -762,8 +756,7 @@ public class AtAjAttributes { || Modifier.isProtected(implModifiers) || Modifier.isPublic(implModifiers)); boolean hasNoCtorOrANoArgOne = true; ResolvedMember foundOneOfIncorrectVisibility = null; - for (int i = 0; i < mm.length; i++) { - ResolvedMember resolvedMember = mm[i]; + for (ResolvedMember resolvedMember : mm) { if (resolvedMember.getName().equals("<init>")) { hasNoCtorOrANoArgOne = false; @@ -994,14 +987,13 @@ public class AtAjAttributes { boolean hasAtLeastOneMethod = false; - for (Iterator<ResolvedType> iterator = newInterfaceTypes.iterator(); iterator.hasNext();) { - ResolvedType typeForDelegation = iterator.next(); + for (ResolvedType typeForDelegation : newInterfaceTypes) { // TODO check for overlapping interfaces. Eg. A implements I, I extends J - if they specify interfaces={I,J} we dont // want to do any methods twice ResolvedMember[] methods = typeForDelegation.getMethodsWithoutIterator(true, false, false).toArray( new ResolvedMember[0]); - for (int i = 0; i < methods.length; i++) { - ResolvedMember method = methods[i]; + for (ResolvedMember resolvedMember : methods) { + ResolvedMember method = resolvedMember; if (method.isAbstract()) { hasAtLeastOneMethod = true; if (method.hasBackingGenericMember()) { @@ -1648,14 +1640,14 @@ public class AtAjAttributes { */ public static int extractExtraArgument(String[] argumentSignatures) { int extraArgument = 0; - for (int i = 0; i < argumentSignatures.length; i++) { - if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) { + for (String argumentSignature : argumentSignatures) { + if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignature)) { extraArgument |= Advice.ThisJoinPoint; - } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) { + } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignature)) { extraArgument |= Advice.ThisJoinPoint; - } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { + } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignature)) { extraArgument |= Advice.ThisJoinPointStaticPart; - } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) { + } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignature)) { extraArgument |= Advice.ThisEnclosingJoinPointStaticPart; } } @@ -1738,8 +1730,7 @@ public class AtAjAttributes { LocalVariableTable lt = method.getLocalVariableTable(); if (lt != null) { LocalVariable[] lvt = lt.getLocalVariableTable(); - for (int j = 0; j < lvt.length; j++) { - LocalVariable localVariable = lvt[j]; + for (LocalVariable localVariable : lvt) { if (localVariable != null) { // pr348488 if (localVariable.getStartPC() == 0) { if (localVariable.getIndex() >= startAtStackIndex) { @@ -1909,8 +1900,7 @@ public class AtAjAttributes { // register ImplicitBindings as to be ignored since unbound // TODO is it likely to fail in a bad way if f.e. this(jp) etc ? List<String> ignores = new ArrayList<String>(); - for (int i = 0; i < bindings.length; i++) { - FormalBinding formalBinding = bindings[i]; + for (FormalBinding formalBinding : bindings) { if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) { ignores.add(formalBinding.getName()); } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAdvice.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAdvice.java index 0c2cadb1f..7736addcd 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAdvice.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAdvice.java @@ -79,8 +79,8 @@ class BcelAdvice extends Advice { public boolean bindsProceedingJoinPoint() { UnresolvedType[] parameterTypes = signature.getParameterTypes(); - for (int i=0;i<parameterTypes.length;i++) { - if (parameterTypes[i].equals(UnresolvedType.PROCEEDING_JOINPOINT)) { + for (UnresolvedType parameterType : parameterTypes) { + if (parameterType.equals(UnresolvedType.PROCEEDING_JOINPOINT)) { return true; } } @@ -428,11 +428,11 @@ class BcelAdvice extends Advice { ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION); ResolvedType error = world.getCoreType(UnresolvedType.ERROR); - for (int i = 0, len = excs.length; i < len; i++) { - ResolvedType t = world.resolve(excs[i], true); + for (UnresolvedType exc : excs) { + ResolvedType t = world.resolve(exc, true); if (t.isMissing()) { world.getLint().cantFindType - .signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE, excs[i].getName()), + .signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE, exc.getName()), getSourceLocation()); // IMessage msg = new Message( // WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()), @@ -546,8 +546,7 @@ class BcelAdvice extends Advice { LocalVariableTable lvt = shadow.getEnclosingMethod().getMemberView().getMethod().getLocalVariableTable(); if (lvt != null) { LocalVariable[] lvTable = lvt.getLocalVariableTable(); - for (int i = 0; i < lvTable.length; i++) { - LocalVariable lv = lvTable[i]; + for (LocalVariable lv : lvTable) { if (lv.getStartPC() == 0) { start.addTargeter(new LocalVariableTag(lv.getSignature(), lv.getName(), lv.getIndex(), 0)); } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAnnotation.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAnnotation.java index 275eae512..b11afc77d 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAnnotation.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelAnnotation.java @@ -76,8 +76,8 @@ public class BcelAnnotation extends AbstractAnnotationAJ { ArrayElementValue aev = (ArrayElementValue) envp.getValue(); ElementValue[] evs = aev.getElementValuesArray(); Set<String> targets = new HashSet<String>(); - for (int i = 0; i < evs.length; i++) { - EnumElementValue ev = (EnumElementValue) evs[i]; + for (ElementValue elementValue : evs) { + EnumElementValue ev = (EnumElementValue) elementValue; targets.add(ev.getEnumValueString()); } return targets; diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelClassWeaver.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelClassWeaver.java index 66ccfd0ce..3c4f64aa2 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelClassWeaver.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelClassWeaver.java @@ -187,10 +187,10 @@ class BcelClassWeaver implements IClassWeaver { private void initializeSuperInitializerMap(ResolvedType child) { ResolvedType[] superInterfaces = child.getDeclaredInterfaces(); - for (int i = 0, len = superInterfaces.length; i < len; i++) { - if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) { - if (addSuperInitializer(superInterfaces[i])) { - initializeSuperInitializerMap(superInterfaces[i]); + for (ResolvedType superInterface : superInterfaces) { + if (ty.getResolvedTypeX().isTopmostImplementor(superInterface)) { + if (addSuperInitializer(superInterface)) { + initializeSuperInitializerMap(superInterface); } } } @@ -512,8 +512,8 @@ class BcelClassWeaver implements IClassWeaver { // now proceed with late type mungers if (lateTypeMungers != null) { - for (Iterator<ConcreteTypeMunger> i = lateTypeMungers.iterator(); i.hasNext();) { - BcelTypeMunger munger = (BcelTypeMunger) i.next(); + for (ConcreteTypeMunger lateTypeMunger : lateTypeMungers) { + BcelTypeMunger munger = (BcelTypeMunger) lateTypeMunger; if (munger.matches(clazz.getType())) { boolean typeMungerAffectedType = munger.munge(this); if (typeMungerAffectedType) { @@ -723,9 +723,8 @@ class BcelClassWeaver implements IClassWeaver { boolean inSamePackage = packageName.equals(mpkg); ResolvedMember[] methods = typeToCheck.getDeclaredMethods(); - for (int ii = 0; ii < methods.length; ii++) { + for (ResolvedMember methodThatMightBeGettingOverridden : methods) { // the method we are going to check - ResolvedMember methodThatMightBeGettingOverridden = methods[ii]; ResolvedMember isOverriding = isOverriding(typeToCheck, methodThatMightBeGettingOverridden, mname, mrettype, mmods, inSamePackage, methodParamsArray); if (isOverriding != null) { @@ -735,8 +734,7 @@ class BcelClassWeaver implements IClassWeaver { // was: List l = typeToCheck.getInterTypeMungers(); List<ConcreteTypeMunger> l = (typeToCheck.isRawType() ? typeToCheck.getGenericType().getInterTypeMungers() : typeToCheck .getInterTypeMungers()); - for (Iterator<ConcreteTypeMunger> iterator = l.iterator(); iterator.hasNext();) { - ConcreteTypeMunger o = iterator.next(); + for (ConcreteTypeMunger o : l) { // FIXME asc if its not a BcelTypeMunger then its an // EclipseTypeMunger ... do I need to worry about that? if (o instanceof BcelTypeMunger) { @@ -763,9 +761,8 @@ class BcelClassWeaver implements IClassWeaver { checkForOverride(superclass, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector); ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - ResolvedType anInterface = interfaces[i]; - checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector); + for (ResolvedType anInterface : interfaces) { + checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray, overriddenMethodsCollector); } } @@ -793,17 +790,15 @@ class BcelClassWeaver implements IClassWeaver { // Keep a set of all methods from this type - it'll help us to check if bridge methods // have already been created, we don't want to do it twice! Set<String> methodsSet = new HashSet<String>(); - for (int i = 0; i < methods.size(); i++) { - LazyMethodGen aMethod = methods.get(i); + for (LazyMethodGen aMethod : methods) { StringBuilder sb = new StringBuilder(aMethod.getName()); sb.append(aMethod.getSignature()); methodsSet.add(sb.toString()); // e.g. "foo(Ljava/lang/String;)V" } // Now go through all the methods in this type - for (int i = 0; i < methods.size(); i++) { + for (LazyMethodGen bridgeToCandidate : methods) { // This is the local method that we *might* have to bridge to - LazyMethodGen bridgeToCandidate = methods.get(i); if (bridgeToCandidate.isBridgeMethod()) { continue; // Doh! } @@ -833,7 +828,7 @@ class BcelClassWeaver implements IClassWeaver { List<ResolvedMember> overriddenMethodsCollector = new ArrayList<ResolvedMember>(); checkForOverride(theSuperclass, name, psig, rsig, bridgeToCandidate.getAccessFlags(), pkgName, bm, overriddenMethodsCollector); if (overriddenMethodsCollector.size() != 0) { - for (ResolvedMember overriddenMethod: overriddenMethodsCollector) { + for (ResolvedMember overriddenMethod : overriddenMethodsCollector) { String key = new StringBuilder(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419 boolean alreadyHaveABridgeMethod = methodsSet.contains(key); if (!alreadyHaveABridgeMethod) { @@ -849,15 +844,15 @@ class BcelClassWeaver implements IClassWeaver { // Check superinterfaces String[] interfaces = clazz.getInterfaceNames(); - for (int j = 0; j < interfaces.length; j++) { + for (String anInterface : interfaces) { if (world.forDEBUG_bridgingCode) { - System.err.println("Bridging:checking superinterface " + interfaces[j]); + System.err.println("Bridging:checking superinterface " + anInterface); } - ResolvedType interfaceType = world.resolve(interfaces[j]); + ResolvedType interfaceType = world.resolve(anInterface); overriddenMethodsCollector.clear(); checkForOverride(interfaceType, name, psig, rsig, bridgeToCandidate.getAccessFlags(), clazz.getPackageName(), bm, overriddenMethodsCollector); - for (ResolvedMember overriddenMethod: overriddenMethodsCollector) { + for (ResolvedMember overriddenMethod : overriddenMethodsCollector) { String key = new StringBuffer().append(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419 boolean alreadyHaveABridgeMethod = methodsSet.contains(key); if (!alreadyHaveABridgeMethod) { @@ -1198,14 +1193,13 @@ class BcelClassWeaver implements IClassWeaver { private boolean weaveAtFieldRepeatedly(List<DeclareAnnotation> decaFs, List<ConcreteTypeMunger> itdFields, List<Integer> reportedErrors) { boolean isChanged = false; - for (Iterator<ConcreteTypeMunger> iter = itdFields.iterator(); iter.hasNext();) { - BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next(); + for (ConcreteTypeMunger itdField : itdFields) { + BcelTypeMunger fieldMunger = (BcelTypeMunger) itdField; ResolvedMember itdIsActually = fieldMunger.getSignature(); Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>(); boolean modificationOccured = false; - for (Iterator<DeclareAnnotation> iter2 = decaFs.iterator(); iter2.hasNext();) { - DeclareAnnotation decaF = iter2.next(); + for (DeclareAnnotation decaF : decaFs) { if (decaF.matches(itdIsActually, world)) { if (decaF.isRemover()) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); @@ -1242,8 +1236,7 @@ class BcelClassWeaver implements IClassWeaver { while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); - for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) { - DeclareAnnotation decaF = iter2.next(); + for (DeclareAnnotation decaF : worthRetrying) { if (decaF.matches(itdIsActually, world)) { if (decaF.isRemover()) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger); @@ -1290,8 +1283,7 @@ class BcelClassWeaver implements IClassWeaver { List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>(); boolean modificationOccured = false; - for (Iterator<DeclareAnnotation> iter2 = decaMCs.iterator(); iter2.hasNext();) { - DeclareAnnotation decaMC = iter2.next(); + for (DeclareAnnotation decaMC : decaMCs) { if (decaMC.matches(unMangledInterMethod, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz, methodctorMunger); if (annotationHolder == null @@ -1315,8 +1307,7 @@ class BcelClassWeaver implements IClassWeaver { while (!worthRetrying.isEmpty() && modificationOccured) { modificationOccured = false; List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); - for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) { - DeclareAnnotation decaMC = iter2.next(); + for (DeclareAnnotation decaMC : worthRetrying) { if (decaMC.matches(unMangledInterMethod, world)) { LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, methodctorMunger); if (doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) { @@ -1453,9 +1444,7 @@ class BcelClassWeaver implements IClassWeaver { modificationOccured = false; // lets have another go with any remaining ones List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>(); - for (Iterator<DeclareAnnotation> iter = worthRetrying.iterator(); iter.hasNext();) { - DeclareAnnotation decaF = iter.next(); - + for (DeclareAnnotation decaF : worthRetrying) { if (decaF.matches(field, world)) { if (decaF.isRemover()) { AnnotationAJ annotation = decaF.getAnnotation(); @@ -1471,7 +1460,7 @@ class BcelClassWeaver implements IClassWeaver { } else { // below code is for recursive things unusedDecafs.remove(decaF); - if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems,true)) { + if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems, true)) { continue; } field.addAnnotation(decaF.getAnnotation()); @@ -1806,8 +1795,7 @@ class BcelClassWeaver implements IClassWeaver { // the load instruction // (so we never jump over the monitorexit logic) - for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) { - InstructionHandle element = iter.next(); + for (InstructionHandle element : rets) { InstructionList monitorExitBlock = new InstructionList(); monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType, slotForLockObject)); monitorExitBlock.append(InstructionConstants.MONITOREXIT); @@ -2125,8 +2113,7 @@ class BcelClassWeaver implements IClassWeaver { // load instruction // (so we never jump over the monitorexit logic) - for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) { - InstructionHandle element = iter.next(); + for (InstructionHandle element : rets) { // System.err.println("Adding monitor exit block at "+element // ); InstructionList monitorExitBlock = new InstructionList(); @@ -2560,8 +2547,7 @@ class BcelClassWeaver implements IClassWeaver { donorFramePos += 1; } Type[] argTypes = donor.getArgumentTypes(); - for (int i = 0, len = argTypes.length; i < len; i++) { - Type argType = argTypes[i]; + for (Type argType : argTypes) { int argSlot = recipient.allocateLocal(argType); ret.insert(InstructionFactory.createStore(argType, argSlot)); frameEnv.put(donorFramePos, argSlot); @@ -2747,9 +2733,7 @@ class BcelClassWeaver implements IClassWeaver { // now add interface inits if (!isThisCall(superOrThisCall)) { InstructionHandle curr = enclosingShadow.getRange().getStart(); - for (Iterator<IfaceInitList> i = addedSuperInitializersAsList.iterator(); i.hasNext();) { - IfaceInitList l = i.next(); - + for (IfaceInitList l : addedSuperInitializersAsList) { Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType); BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig); @@ -3041,8 +3025,7 @@ class BcelClassWeaver implements IClassWeaver { */ private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName) { ResolvedMember[] allMethods = type.getDeclaredMethods(); - for (int i = 0; i < allMethods.length; i++) { - ResolvedMember member = allMethods[i]; + for (ResolvedMember member : allMethods) { if (member.getName().equals(methodName)) { return member; } @@ -3060,8 +3043,7 @@ class BcelClassWeaver implements IClassWeaver { private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName, UnresolvedType[] params) { ResolvedMember[] allMethods = type.getDeclaredMethods(); List<ResolvedMember> candidates = new ArrayList<ResolvedMember>(); - for (int i = 0; i < allMethods.length; i++) { - ResolvedMember candidate = allMethods[i]; + for (ResolvedMember candidate : allMethods) { if (candidate.getName().equals(methodName)) { if (candidate.getArity() == params.length) { candidates.add(candidate); diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXConverter.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXConverter.java index 9b4c90cbc..7f6c70d72 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXConverter.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelGenericSignatureToTypeXConverter.java @@ -208,9 +208,9 @@ public class BcelGenericSignatureToTypeXConverter { Map<GenericSignature.FormalTypeParameter, ReferenceType> inProgressTypeVariableResolutions) throws GenericSignatureFormatException { GenericSignature.FormalTypeParameter typeVarBounds = null; - for (int i = 0; i < typeParams.length; i++) { - if (typeParams[i].identifier.equals(aTypeVarSig.typeVariableName)) { - typeVarBounds = typeParams[i]; + for (GenericSignature.FormalTypeParameter typeParam : typeParams) { + if (typeParam.identifier.equals(aTypeVarSig.typeVariableName)) { + typeVarBounds = typeParam; break; } } @@ -240,10 +240,10 @@ public class BcelGenericSignatureToTypeXConverter { ReferenceType rt = (ReferenceType) aTypeX; TypeVariable[] typeVars = rt.getTypeVariables(); if (typeVars != null) { - for (int i = 0; i < typeVars.length; i++) { - if (typeVars[i].getUpperBound() instanceof FTPHolder) { - GenericSignature.FormalTypeParameter key = ((FTPHolder) typeVars[i].getUpperBound()).ftpToBeSubstituted; - typeVars[i].setUpperBound(typeVariableResolutions.get(key)); + for (TypeVariable typeVar : typeVars) { + if (typeVar.getUpperBound() instanceof FTPHolder) { + GenericSignature.FormalTypeParameter key = ((FTPHolder) typeVar.getUpperBound()).ftpToBeSubstituted; + typeVar.setUpperBound(typeVariableResolutions.get(key)); } } } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelMethod.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelMethod.java index d1e60e1c7..6da16be27 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelMethod.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelMethod.java @@ -141,8 +141,7 @@ class BcelMethod extends ResolvedMemberImpl { AnnotationAJ[] annos = getAnnotations(); if (annos != null && annos.length != 0) { AnnotationAJ[] axs = getAnnotations(); - for (int i = 0; i < axs.length; i++) { - AnnotationAJ annotationX = axs[i]; + for (AnnotationAJ annotationX : axs) { String typename = annotationX.getTypeName(); if (typename.charAt(0) == PACKAGE_INITIAL_CHAR) { if (typename.equals("org.aspectj.lang.annotation.Pointcut") @@ -164,7 +163,7 @@ class BcelMethod extends ResolvedMemberImpl { while (argsList.size() < requiredCount) { argsList.add("arg" + argsList.size()); } - setParameterNames(argsList.toArray(new String[] {})); + setParameterNames(argsList.toArray(new String[]{})); return; } } @@ -246,8 +245,7 @@ class BcelMethod extends ResolvedMemberImpl { @Override public String getAnnotationDefaultValue() { Attribute[] attrs = method.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals("AnnotationDefault")) { AnnotationDefault def = (AnnotationDefault) attribute; return def.getElementValue().stringifyValue(); @@ -261,9 +259,9 @@ class BcelMethod extends ResolvedMemberImpl { Attribute[] as = method.getAttributes(); List<String> names = new ArrayList<String>(); // String[] strs = new String[as.length]; - for (int j = 0; j < as.length; j++) { - if (!onlyIncludeAjOnes || as[j].getName().startsWith(AjAttribute.AttributePrefix)) { - names.add(as[j].getName()); + for (Attribute a : as) { + if (!onlyIncludeAjOnes || a.getName().startsWith(AjAttribute.AttributePrefix)) { + names.add(a.getName()); } } return names.toArray(new String[] {}); @@ -361,9 +359,9 @@ class BcelMethod extends ResolvedMemberImpl { if ((bitflags & HAS_ANNOTATIONS) == 0) { return null; } - for (int i = 0; i < annotations.length; i++) { - if (annotations[i].getTypeName().equals(ofType.getName())) { - return annotations[i]; + for (AnnotationAJ annotation : annotations) { + if (annotation.getTypeName().equals(ofType.getName())) { + return annotation; } } return null; @@ -660,8 +658,8 @@ class BcelMethod extends ResolvedMemberImpl { // synthetic is an attribute String[] synthetics = getAttributeNames(false); if (synthetics != null) { - for (int i = 0; i < synthetics.length; i++) { - if (synthetics[i].equals("Synthetic")) { + for (String synthetic : synthetics) { + if (synthetic.equals("Synthetic")) { bitflags |= IS_SYNTHETIC; break; } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelObjectType.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelObjectType.java index 710eb6dc7..b7ce3f842 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelObjectType.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelObjectType.java @@ -462,8 +462,7 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { private void resolveAnnotationDeclares(List<AjAttribute> attributeList) { FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0]; IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings); - for (Iterator<AjAttribute> iter = attributeList.iterator(); iter.hasNext();) { - AjAttribute a = iter.next(); + for (AjAttribute a : attributeList) { if (a instanceof AjAttribute.DeclareAttribute) { Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare()); if (decl instanceof DeclareErrorOrWarning) { @@ -605,8 +604,7 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { return false; } else { String lookingForSignature = ofType.getSignature(); - for (int a = 0; a < annos.length; a++) { - AnnotationGen annotation = annos[a]; + for (AnnotationGen annotation : annos) { if (lookingForSignature.equals(annotation.getTypeSignature())) { return true; } @@ -641,8 +639,7 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { AnnotationAJ ax = annotations[i]; if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) { List<NameValuePair> values = ((BcelAnnotation) ax).getBcelAnnotation().getValues(); - for (Iterator<NameValuePair> it = values.iterator(); it.hasNext();) { - NameValuePair element = it.next(); + for (NameValuePair element : values) { EnumElementValue v = (EnumElementValue) element.getValue(); retentionPolicy = v.getEnumValueString(); return retentionPolicy; @@ -659,8 +656,8 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { if (targetKinds == null) { return true; } - for (int i = 0; i < targetKinds.length; i++) { - if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) { + for (AnnotationTargetKind targetKind : targetKinds) { + if (targetKind.equals(AnnotationTargetKind.TYPE)) { return true; } } @@ -677,8 +674,7 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>(); if (isAnnotation()) { AnnotationAJ[] annotationsOnThisType = getAnnotations(); - for (int i = 0; i < annotationsOnThisType.length; i++) { - AnnotationAJ a = annotationsOnThisType[i]; + for (AnnotationAJ a : annotationsOnThisType) { if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) { Set<String> targets = a.getTargets(); if (targets != null) { @@ -775,11 +771,11 @@ public class BcelObjectType extends AbstractReferenceTypeDelegate { GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass(); if (extraFormals.length > 0) { List<FormalTypeParameter> allFormals = new ArrayList<FormalTypeParameter>(); - for (int i = 0; i < formalsForResolution.length; i++) { - allFormals.add(formalsForResolution[i]); + for (FormalTypeParameter formalTypeParameter : formalsForResolution) { + allFormals.add(formalTypeParameter); } - for (int i = 0; i < extraFormals.length; i++) { - allFormals.add(extraFormals[i]); + for (FormalTypeParameter extraFormal : extraFormals) { + allFormals.add(extraFormal); } formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()]; allFormals.toArray(formalsForResolution); diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelShadow.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelShadow.java index adb7fc921..ca167e2ef 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelShadow.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelShadow.java @@ -157,8 +157,8 @@ public class BcelShadow extends Shadow { s.mungers = new ArrayList<ShadowMunger>(); } List<ShadowMunger> dest = s.mungers; - for (Iterator<ShadowMunger> i = src.iterator(); i.hasNext();) { - dest.add(i.next()); + for (ShadowMunger shadowMunger : src) { + dest.add(shadowMunger); } } return s; @@ -365,8 +365,7 @@ public class BcelShadow extends Shadow { // something stopped us making it a lazy tjp // can't build tjp lazily, no suitable test... int valid = 0; - for (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) { - BcelAdvice element = iter.next(); + for (BcelAdvice element : badAdvice) { ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null && sLoc.getLine() > 0) { valid++; @@ -375,8 +374,7 @@ public class BcelShadow extends Shadow { if (valid != 0) { ISourceLocation[] badLocs = new ISourceLocation[valid]; int i = 0; - for (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) { - BcelAdvice element = iter.next(); + for (BcelAdvice element : badAdvice) { ISourceLocation sLoc = element.getSourceLocation(); if (sLoc != null) { badLocs[i++] = sLoc; @@ -1047,14 +1045,13 @@ public class BcelShadow extends Shadow { private boolean checkLazyTjp() { // check for around advice - for (Iterator<ShadowMunger> i = mungers.iterator(); i.hasNext();) { - ShadowMunger munger = i.next(); + for (ShadowMunger munger : mungers) { if (munger instanceof Advice) { if (((Advice) munger).getKind() == AdviceKind.Around) { if (munger.getSourceLocation() != null) { // do we know enough to bother reporting? if (world.getLint().canNotImplementLazyTjp.isEnabled()) { - world.getLint().canNotImplementLazyTjp.signal(new String[] { toString() }, getSourceLocation(), - new ISourceLocation[] { munger.getSourceLocation() }); + world.getLint().canNotImplementLazyTjp.signal(new String[]{toString()}, getSourceLocation(), + new ISourceLocation[]{munger.getSourceLocation()}); } } return false; @@ -1454,8 +1451,7 @@ public class BcelShadow extends Shadow { ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent // gotten yet but we will get in // subclasses? - for (int i = 0; i < rtx.length; i++) { - ResolvedType typeX = rtx[i]; + for (ResolvedType typeX : rtx) { targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar())); } // populate. @@ -1517,8 +1513,7 @@ public class BcelShadow extends Shadow { if (foundMember == null) { // check the ITD'd dooberries List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers(); - for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) { - Object munger = iter.next(); + for (Object munger : mungers) { ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger; if (typeMunger.getMunger() instanceof NewMethodTypeMunger || typeMunger.getMunger() instanceof NewConstructorTypeMunger) { @@ -1639,8 +1634,7 @@ public class BcelShadow extends Shadow { private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) { ResolvedMember decMethods[] = aspectType.getDeclaredMethods(); - for (int i = 0; i < decMethods.length; i++) { - ResolvedMember member = decMethods[i]; + for (ResolvedMember member : decMethods) { if (member.equals(ajcMethod)) { return member; } @@ -1649,8 +1643,7 @@ public class BcelShadow extends Shadow { } private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) { - for (int i = 0; i < members.length; i++) { - ResolvedMember member = members[i]; + for (ResolvedMember member : members) { if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) { return member; } @@ -1665,8 +1658,7 @@ public class BcelShadow extends Shadow { withinAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>(); ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes(); - for (int i = 0; i < annotations.length; i++) { - ResolvedType ann = annotations[i]; + for (ResolvedType ann : annotations) { Kind k = Shadow.StaticInitialization; withinAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(), null, true)); } @@ -1680,8 +1672,7 @@ public class BcelShadow extends Shadow { // For some shadow we are interested in annotations on the method containing that shadow. ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes(); - for (int i = 0; i < annotations.length; i++) { - ResolvedType ann = annotations[i]; + for (ResolvedType ann : annotations) { Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution : Shadow.MethodExecution); withincodeAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(), @@ -1732,8 +1723,7 @@ public class BcelShadow extends Shadow { if (hasReturnInstructions) { InstructionHandle gotoTarget = advice.getStart(); - for (Iterator<InstructionHandle> i = returns.iterator(); i.hasNext();) { - InstructionHandle ih = i.next(); + for (InstructionHandle ih : returns) { retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih); } } @@ -2299,8 +2289,7 @@ public class BcelShadow extends Shadow { InstructionList advice = new InstructionList(); // InstructionHandle adviceMethodInvocation; { - for (Iterator<BcelVar> i = argsToCallLocalAdviceMethodWith.iterator(); i.hasNext();) { - BcelVar var = i.next(); + for (BcelVar var : argsToCallLocalAdviceMethodWith) { var.appendLoad(advice, fact); } // ??? we don't actually need to push NULL for the closure if we take care @@ -3255,9 +3244,9 @@ public class BcelShadow extends Shadow { if (targetVar != null && targetVar != thisVar) { ret.put(targetVar.getSlot(), reti++); } - for (int i = 0, len = argVars.length; i < len; i++) { - ret.put(argVars[i].getSlot(), reti); - reti += argVars[i].getType().getSize(); + for (BcelVar argVar : argVars) { + ret.put(argVar.getSlot(), reti); + reti += argVar.getType().getSize(); } if (thisJoinPointVar != null) { ret.put(thisJoinPointVar.getSlot(), reti++); diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelTypeMunger.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelTypeMunger.java index b92760fe9..1eae17682 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelTypeMunger.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelTypeMunger.java @@ -672,8 +672,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member)); return true; } else if (member.getKind() == Member.CONSTRUCTOR) { - for (Iterator<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) { - LazyMethodGen m = i.next(); + for (LazyMethodGen m : gen.getMethodGens()) { if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) { // m.getMemberView().equals(member)) { m.forcePublic(); @@ -743,8 +742,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { il.append(InstructionConstants.ALOAD_0); pos++; } - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { il.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } @@ -975,8 +973,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes()); - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } @@ -1111,8 +1108,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { body.append(InstructionFactory.createThis()); pos++; } - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } @@ -1266,8 +1262,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { // Step1 boolean alreadyDone = false; // Compiler might have done it ResolvedMember[] localMethods = onType.getDeclaredMethods(); - for (int i = 0; i < localMethods.length; i++) { - ResolvedMember member = localMethods[i]; + for (ResolvedMember member : localMethods) { if (member.getName().equals(localMethodName)) { // Check the params if (member.getParameterSignature().equals(localParameterSig)) { @@ -1327,8 +1322,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { body.append(InstructionFactory.createThis()); pos++; } - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { body.append(InstructionFactory.createLoad(paramType, pos)); // if (!bridgingSetter.getParameterTypes()[i].getErasureSignature(). // equals @@ -1510,8 +1504,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { pos++; } Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes()); - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } @@ -1695,8 +1688,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { annotationsOnRealMember = realMember.getAnnotations(); } if (annotationsOnRealMember != null) { - for (int i = 0; i < annotationsOnRealMember.length; i++) { - AnnotationAJ annotationX = annotationsOnRealMember[i]; + for (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld())); @@ -1706,8 +1698,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { // case where an aspect declares an annotation // on an ITD it declared on itself. List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods(); - for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) { - DeclareAnnotation decaMC = i.next(); + for (DeclareAnnotation decaMC : allDecams) { if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) { mg.addAnnotation(decaMC.getAnnotation()); } @@ -1818,8 +1809,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { body.append(InstructionFactory.createThis()); pos++; - for (int i = 0, len = paramTypes.length; i < len; i++) { - Type paramType = paramTypes[i]; + for (Type paramType : paramTypes) { body.append(InstructionFactory.createLoad(paramType, pos)); pos += paramType.getSize(); } @@ -1893,8 +1883,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { FieldGen fg = makeFieldGen(gen, newField); if (annotationsOnRealMember != null) { - for (int i = 0; i < annotationsOnRealMember.length; i++) { - AnnotationAJ annotationX = annotationsOnRealMember[i]; + for (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); @@ -1941,8 +1930,7 @@ public class BcelTypeMunger extends ConcreteTypeMunger { weaver.addInitializer(this); FieldGen fg = makeFieldGen(gen,newField); if (annotationsOnRealMember != null) { - for (int i = 0; i < annotationsOnRealMember.length; i++) { - AnnotationAJ annotationX = annotationsOnRealMember[i]; + for (AnnotationAJ annotationX : annotationsOnRealMember) { AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation(); AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true); fg.addAnnotation(ag); diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWeaver.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWeaver.java index 1b68d27d5..41cbf9a7a 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWeaver.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWeaver.java @@ -361,8 +361,8 @@ public class BcelWeaver { }); // For each file, add it either as a real .class file or as a resource - for (int i = 0; i < files.length; i++) { - addedClassFiles.add(addClassFile(files[i], inFile, outDir)); + for (File file : files) { + addedClassFiles.add(addClassFile(file, inFile, outDir)); } return addedClassFiles; @@ -501,8 +501,7 @@ public class BcelWeaver { needToReweaveWorld = xcutSet.hasChangedSinceLastReset(); // update mungers - for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) { - UnwovenClassFile jc = i.next(); + for (UnwovenClassFile jc : addedClasses) { String name = jc.getClassName(); ResolvedType type = world.resolve(name); // No overweaving guard. If you have one then when overweaving is on the @@ -514,8 +513,7 @@ public class BcelWeaver { } } - for (Iterator<String> i = deletedTypenames.iterator(); i.hasNext();) { - String name = i.next(); + for (String name : deletedTypenames) { if (xcutSet.deleteAspect(UnresolvedType.forName(name))) { needToReweaveWorld = true; } @@ -574,8 +572,7 @@ public class BcelWeaver { private void addCustomMungers() { if (customMungerFactory != null) { - for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) { - UnwovenClassFile jc = i.next(); + for (UnwovenClassFile jc : addedClasses) { String name = jc.getClassName(); ResolvedType type = world.resolve(name); if (type.isAspect()) { @@ -822,12 +819,12 @@ public class BcelWeaver { } else if (pc instanceof ConcreteCflowPointcut) { ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc; int[] slots = cfp.getUsedFormalSlots(); - for (int i = 0; i < slots.length; i++) { - bindings[slots[i]] = cfp; - if (foundFormals[slots[i]]) { - raiseAmbiguousBindingError(names[slots[i]], userPointcut); + for (int slot : slots) { + bindings[slot] = cfp; + if (foundFormals[slot]) { + raiseAmbiguousBindingError(names[slot], userPointcut); } else { - foundFormals[slots[i]] = true; + foundFormals[slot] = true; } } } @@ -1065,8 +1062,8 @@ public class BcelWeaver { selfMunger.forceMunge(clazz, true); classType.finishedWith(); UnwovenClassFile[] newClasses = getClassFilesFor(clazz); - for (int news = 0; news < newClasses.length; news++) { - requestor.acceptResult(newClasses[news]); + for (UnwovenClassFile newClass : newClasses) { + requestor.acceptResult(newClass); } wovenClassNames.add(classFile.getClassName()); } @@ -1260,8 +1257,8 @@ public class BcelWeaver { List l = world.getCrosscuttingMembersSet().getShadowMungers(); Set<AdviceLocation> alreadyWarnedLocations = new HashSet<AdviceLocation>(); - for (Iterator iter = l.iterator(); iter.hasNext();) { - ShadowMunger element = (ShadowMunger) iter.next(); + for (Object o : l) { + ShadowMunger element = (ShadowMunger) o; // This will stop us incorrectly reporting deow checkers: if (element instanceof BcelAdvice) { BcelAdvice ba = (BcelAdvice) element; @@ -1430,8 +1427,8 @@ public class BcelWeaver { if (newClasses[0].getClassName().equals(classFile.getClassName())) { newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars()); } - for (int i = 0; i < newClasses.length; i++) { - requestor.acceptResult(newClasses[i]); + for (UnwovenClassFile newClass : newClasses) { + requestor.acceptResult(newClass); } } else { requestor.acceptResult(classFile); @@ -1462,8 +1459,7 @@ public class BcelWeaver { UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()]; ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world)); int index = 1; - for (Iterator<UnwovenClassFile.ChildClass> iter = childClasses.iterator(); iter.hasNext();) { - UnwovenClassFile.ChildClass element = iter.next(); + for (UnwovenClassFile.ChildClass element : childClasses) { UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes); ret[index++] = childClass; } @@ -1509,8 +1505,7 @@ public class BcelWeaver { while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) { anAnnotationChangeOccurred = aParentChangeOccurred = false; List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>(); - for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) { - DeclareParents decp = iter.next(); + for (DeclareParents decp : decpToRepeat) { boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; @@ -1929,8 +1924,7 @@ public class BcelWeaver { writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes()); List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world); if (!childClasses.isEmpty()) { - for (Iterator<UnwovenClassFile.ChildClass> i = childClasses.iterator(); i.hasNext();) { - UnwovenClassFile.ChildClass c = i.next(); + for (UnwovenClassFile.ChildClass c : childClasses) { writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWorld.java b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWorld.java index 4ade1e125..1ee675655 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWorld.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/BcelWorld.java @@ -885,8 +885,7 @@ public class BcelWorld extends World implements Repository { boolean aParentChangeOccurred = false; boolean anAnnotationChangeOccurred = false; // First pass - apply all decp mungers - for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) { - DeclareParents decp = i.next(); + for (DeclareParents decp : declareParentsList) { boolean typeChanged = applyDeclareParents(decp, onType); if (typeChanged) { aParentChangeOccurred = true; diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/ClassPathManager.java b/weaver/src/main/java/org/aspectj/weaver/bcel/ClassPathManager.java index b7f68ca45..fa45b7df6 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/ClassPathManager.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/ClassPathManager.java @@ -160,13 +160,13 @@ public class ClassPathManager { public String toString() { StringBuffer buf = new StringBuffer(); boolean start = true; - for (Iterator<Entry> i = entries.iterator(); i.hasNext();) { + for (Entry entry : entries) { if (start) { start = false; } else { buf.append(File.pathSeparator); } - buf.append(i.next()); + buf.append(entry); } return buf.toString(); } diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/LazyClassGen.java b/weaver/src/main/java/org/aspectj/weaver/bcel/LazyClassGen.java index 57761bbdf..c8185d1c2 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/LazyClassGen.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/LazyClassGen.java @@ -331,15 +331,14 @@ public final class LazyClassGen { hasSerialVersionUIDField = hasSerialVersionUIDField(getType()); ResolvedMember[] methods = getType().getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - ResolvedMember method = methods[i]; - if (method.getName().equals("<clinit>")) { - if (method.getKind() != Member.STATIC_INITIALIZATION) { - throw new RuntimeException("qui?"); - } - hasClinit = true; - } - } + for (ResolvedMember method : methods) { + if (method.getName().equals("<clinit>")) { + if (method.getKind() != Member.STATIC_INITIALIZATION) { + throw new RuntimeException("qui?"); + } + hasClinit = true; + } + } // Do we need to calculate an SUID and add it? if (!getType().isInterface() && !hasSerialVersionUIDField && world.isAddSerialVerUID()) { @@ -358,9 +357,9 @@ public final class LazyClassGen { } ResolvedMember[] methods = myType.getDeclaredMethods(); - for (int i = 0; i < methods.length; i++) { - addMethodGen(new LazyMethodGen((BcelMethod) methods[i], this)); - } + for (ResolvedMember method : methods) { + addMethodGen(new LazyMethodGen((BcelMethod) method, this)); + } // Method[] methods = myGen.getMethods(); // for (int i = 0; i < methods.length; i++) { @@ -368,21 +367,20 @@ public final class LazyClassGen { // } ResolvedMember[] fields = myType.getDeclaredFields(); - for (int i = 0; i < fields.length; i++) { - this.fields.add((BcelField) fields[i]); - } + for (ResolvedMember field : fields) { + this.fields.add((BcelField) field); + } } public static boolean hasSerialVersionUIDField(ResolvedType type) { ResolvedMember[] fields = type.getDeclaredFields(); - for (int i = 0; i < fields.length; i++) { - ResolvedMember field = fields[i]; - if (field.getName().equals("serialVersionUID") && Modifier.isStatic(field.getModifiers()) - && field.getType().equals(UnresolvedType.LONG)) { - return true; - } - } + for (ResolvedMember field : fields) { + if (field.getName().equals("serialVersionUID") && Modifier.isStatic(field.getModifiers()) + && field.getType().equals(UnresolvedType.LONG)) { + return true; + } + } return false; } @@ -646,19 +644,17 @@ public final class LazyClassGen { if (!needAttribute) { if (myType != null) { ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); - for (int i = 0; i < interfaceRTXs.length; i++) { - ResolvedType typeX = interfaceRTXs[i]; - if (typeX.isGenericType() || typeX.isParameterizedType()) { - needAttribute = true; - } - } + for (ResolvedType typeX : interfaceRTXs) { + if (typeX.isGenericType() || typeX.isParameterizedType()) { + needAttribute = true; + } + } if (extraSuperInterfaces != null) { - for (int i = 0; i < extraSuperInterfaces.length; i++) { - ResolvedType interfaceType = extraSuperInterfaces[i]; - if (interfaceType.isGenericType() || interfaceType.isParameterizedType()) { - needAttribute = true; - } - } + for (ResolvedType interfaceType : extraSuperInterfaces) { + if (interfaceType.isGenericType() || interfaceType.isParameterizedType()) { + needAttribute = true; + } + } } } @@ -685,10 +681,9 @@ public final class LazyClassGen { TypeVariable[] tVars = myType.getTypeVariables(); if (tVars.length > 0) { signature.append("<"); - for (int i = 0; i < tVars.length; i++) { - TypeVariable variable = tVars[i]; - signature.append(variable.getSignatureForAttribute()); - } + for (TypeVariable variable : tVars) { + signature.append(variable.getSignatureForAttribute()); + } signature.append(">"); } } @@ -697,15 +692,15 @@ public final class LazyClassGen { signature.append(supersig); if (myType != null) { ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces(); - for (int i = 0; i < interfaceRTXs.length; i++) { - String s = interfaceRTXs[i].getSignatureForAttribute(); - signature.append(s); - } + for (ResolvedType interfaceRTX : interfaceRTXs) { + String s = interfaceRTX.getSignatureForAttribute(); + signature.append(s); + } if (extraSuperInterfaces != null) { - for (int i = 0; i < extraSuperInterfaces.length; i++) { - String s = extraSuperInterfaces[i].getSignatureForAttribute(); - signature.append(s); - } + for (ResolvedType extraSuperInterface : extraSuperInterfaces) { + String s = extraSuperInterface.getSignatureForAttribute(); + signature.append(s); + } } } if (sigAttr != null) { @@ -905,10 +900,10 @@ public final class LazyClassGen { myType.printWackyStuff(out); } Field[] fields = myGen.getFields(); - for (int i = 0, len = fields.length; i < len; i++) { - out.print(" "); - out.println(fields[i]); - } + for (Field field : fields) { + out.print(" "); + out.println(field); + } List<LazyMethodGen> methodGens = getMethodGens(); for (Iterator<LazyMethodGen> iter = methodGens.iterator(); iter.hasNext();) { LazyMethodGen gen = iter.next(); @@ -1273,16 +1268,15 @@ public final class LazyClassGen { }); long estimatedSize = 0; - for (Iterator<Map.Entry<BcelShadow, Field>> i = entries.iterator(); i.hasNext();) { - Map.Entry<BcelShadow, Field> entry = i.next(); - if (estimatedSize > Constants.MAX_CODE_SIZE) { - estimatedSize = 0; - list = initInstructionList(); - lists.add(list); - } - estimatedSize += entry.getValue().getSignature().getBytes().length; - initializeTjp(fact, list, entry.getValue(), entry.getKey()); - } + for (Map.Entry<BcelShadow, Field> entry : entries) { + if (estimatedSize > Constants.MAX_CODE_SIZE) { + estimatedSize = 0; + list = initInstructionList(); + lists.add(list); + } + estimatedSize += entry.getValue().getSignature().getBytes().length; + initializeTjp(fact, list, entry.getValue(), entry.getKey()); + } InstructionList listArrayModel[] = new InstructionList[1]; return lists.toArray(listArrayModel); } @@ -1779,11 +1773,11 @@ public final class LazyClassGen { } private boolean hasSyntheticAttribute(List<Attribute> attributes) { - for (int i = 0; i < attributes.size(); i++) { - if ((attributes.get(i)).getName().equals("Synthetic")) { - return true; - } - } + for (Attribute attribute : attributes) { + if (attribute.getName().equals("Synthetic")) { + return true; + } + } return false; } @@ -1839,12 +1833,11 @@ public final class LazyClassGen { if (agens == null) { return false; } - for (int i = 0; i < agens.length; i++) { - AnnotationGen gen = agens[i]; - if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) { - return true; - } - } + for (AnnotationGen gen : agens) { + if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) { + return true; + } + } // annotations added during this weave @@ -1884,14 +1877,14 @@ public final class LazyClassGen { } ResolvedType[] interfaces = aType.getDeclaredInterfaces(); - for (int i = 0; i < interfaces.length; i++) { - if (interfaces[i].isMissing()) { - continue; - } - if (implementsSerializable(interfaces[i])) { - return true; - } - } + for (ResolvedType anInterface : interfaces) { + if (anInterface.isMissing()) { + continue; + } + if (implementsSerializable(anInterface)) { + return true; + } + } ResolvedType superType = aType.getSuperclass(); if (superType != null && !superType.isMissing()) { return implementsSerializable(superType); diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/LazyMethodGen.java b/weaver/src/main/java/org/aspectj/weaver/bcel/LazyMethodGen.java index 2655a3456..ed9dd2c7a 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/LazyMethodGen.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/LazyMethodGen.java @@ -966,8 +966,8 @@ public final class LazyMethodGen implements Traceable { } MethodGen gen = new MethodGen(flags, getReturnType(), getArgumentTypes(), null, // getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPool()); - for (int i = 0, len = declaredExceptions.length; i < len; i++) { - gen.addException(declaredExceptions[i]); + for (String declaredException : declaredExceptions) { + gen.addException(declaredException); } for (Attribute attr : attributes) { @@ -983,17 +983,17 @@ public final class LazyMethodGen implements Traceable { if (newParameterAnnotations != null) { for (int i = 0; i < newParameterAnnotations.length; i++) { AnnotationAJ[] annos = newParameterAnnotations[i]; - for (int j = 0; j < annos.length; j++) { + for (AnnotationAJ anno : annos) { gen.addParameterAnnotation(i, - new AnnotationGen(((BcelAnnotation) annos[j]).getBcelAnnotation(), gen.getConstantPool(), true)); + new AnnotationGen(((BcelAnnotation) anno).getBcelAnnotation(), gen.getConstantPool(), true)); } } } if (memberView != null && memberView.getAnnotations() != null && memberView.getAnnotations().length != 0) { AnnotationAJ[] ans = memberView.getAnnotations(); - for (int i = 0, len = ans.length; i < len; i++) { - AnnotationGen a = ((BcelAnnotation) ans[i]).getBcelAnnotation(); + for (AnnotationAJ an : ans) { + AnnotationGen a = ((BcelAnnotation) an).getBcelAnnotation(); gen.addAnnotation(new AnnotationGen(a, gen.getConstantPool(), true)); } } @@ -1315,8 +1315,8 @@ public final class LazyMethodGen implements Traceable { int paramSlots = gen.isStatic() ? 0 : 1; Type[] argTypes = gen.getArgumentTypes(); if (argTypes != null) { - for (int i = 0; i < argTypes.length; i++) { - if (argTypes[i].getSize() == 2) { + for (Type argType : argTypes) { + if (argType.getSize() == 2) { paramSlots += 2; } else { paramSlots += 1; diff --git a/weaver/src/main/java/org/aspectj/weaver/bcel/Utility.java b/weaver/src/main/java/org/aspectj/weaver/bcel/Utility.java index 4acf032fc..7279070bc 100644 --- a/weaver/src/main/java/org/aspectj/weaver/bcel/Utility.java +++ b/weaver/src/main/java/org/aspectj/weaver/bcel/Utility.java @@ -669,9 +669,9 @@ public class Utility { // We know the value is an array value ArrayElementValue array = (ArrayElementValue) (vals.get(0)).getValue(); ElementValue[] values = array.getElementValuesArray(); - for (int j = 0; j < values.length; j++) { + for (ElementValue elementValue : values) { // We know values in the array are strings - SimpleElementValue value = (SimpleElementValue) values[j]; + SimpleElementValue value = (SimpleElementValue) elementValue; Lint.Kind lintKind = lint.getLintKind(value.getValueString()); if (lintKind != null) { suppressedWarnings.add(lintKind); diff --git a/weaver/src/main/java/org/aspectj/weaver/loadtime/definition/SimpleAOPParser.java b/weaver/src/main/java/org/aspectj/weaver/loadtime/definition/SimpleAOPParser.java index 55166f737..e49988a89 100644 --- a/weaver/src/main/java/org/aspectj/weaver/loadtime/definition/SimpleAOPParser.java +++ b/weaver/src/main/java/org/aspectj/weaver/loadtime/definition/SimpleAOPParser.java @@ -254,8 +254,8 @@ public class SimpleAOPParser { throws Exception { sap.startElement(xml.getName(), xml.getAttributes()); ArrayList childrens = xml.getChildrens(); - for (int i = 0; i < childrens.size(); i++) { - LightXMLParser child = (LightXMLParser) childrens.get(i); + for (Object children : childrens) { + LightXMLParser child = (LightXMLParser) children; traverse(sap, child); } sap.endElement(xml.getName()); diff --git a/weaver/src/main/java/org/aspectj/weaver/ltw/LTWWorld.java b/weaver/src/main/java/org/aspectj/weaver/ltw/LTWWorld.java index de5a4d854..1fc72dd06 100644 --- a/weaver/src/main/java/org/aspectj/weaver/ltw/LTWWorld.java +++ b/weaver/src/main/java/org/aspectj/weaver/ltw/LTWWorld.java @@ -193,9 +193,9 @@ public class LTWWorld extends BcelWorld implements IReflectionWorld { String betterChoices[] = { "java.util.concurrent.ConcurrentHashMap", "edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap", "EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap" }; - for (int i = 0; i < betterChoices.length; i++) { + for (String betterChoice : betterChoices) { try { - return Class.forName(betterChoices[i]); + return Class.forName(betterChoice); } catch (ClassNotFoundException cnfe) { // try the next one } catch (SecurityException se) { diff --git a/weaver/src/main/java/org/aspectj/weaver/model/AsmRelationshipProvider.java b/weaver/src/main/java/org/aspectj/weaver/model/AsmRelationshipProvider.java index 5801397a8..2e8a91291 100644 --- a/weaver/src/main/java/org/aspectj/weaver/model/AsmRelationshipProvider.java +++ b/weaver/src/main/java/org/aspectj/weaver/model/AsmRelationshipProvider.java @@ -604,8 +604,7 @@ public class AsmRelationshipProvider { private static void addPointcuts(AsmManager model, String sourcefilename, ResolvedType aspect, IProgramElement containingAspect, ResolvedMember[] pointcuts) { - for (int i = 0; i < pointcuts.length; i++) { - ResolvedMember pointcut = pointcuts[i]; + for (ResolvedMember pointcut : pointcuts) { if (pointcut instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pointcut; Pointcut p = rpcd.getPointcut(); @@ -624,8 +623,7 @@ public class AsmRelationshipProvider { private static final String NO_COMMENT = null; private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, ResolvedMember[] children) { - for (int i = 0; i < children.length; i++) { - ResolvedMember pcd = children[i]; + for (ResolvedMember pcd : children) { if (pcd instanceof ResolvedPointcutDefinition) { ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pcd; Pointcut p = rpcd.getPointcut(); @@ -767,8 +765,8 @@ public class AsmRelationshipProvider { pe.setParameterSignatures(Collections.<char[]>emptyList(), Collections.<String>emptyList()); } else { List<char[]> paramSigs = new ArrayList<char[]>(); - for (int i = 0; i < ts.length; i++) { - paramSigs.add(ts[i].getSignature().toCharArray()); + for (UnresolvedType t : ts) { + paramSigs.add(t.getSignature().toCharArray()); } pe.setParameterSignatures(paramSigs, Collections.<String>emptyList()); } @@ -944,8 +942,7 @@ public class AsmRelationshipProvider { */ private static IProgramElement findOrCreateCodeNode(AsmManager asm, IProgramElement enclosingNode, Member shadowSig, Shadow shadow) { - for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) { - IProgramElement node = (IProgramElement) it.next(); + for (IProgramElement node : enclosingNode.getChildren()) { int excl = node.getBytecodeName().lastIndexOf('!'); if (((excl != -1 && shadowSig.getName().equals(node.getBytecodeName().substring(0, excl))) || shadowSig.getName() .equals(node.getBytecodeName())) @@ -984,8 +981,7 @@ public class AsmRelationshipProvider { if (typeElement == null) { return null; } - for (Iterator it = typeElement.getChildren().iterator(); it.hasNext();) { - IProgramElement element = (IProgramElement) it.next(); + for (IProgramElement element : typeElement.getChildren()) { if (member.getName().equals(element.getBytecodeName()) && member.getSignature().equals(element.getBytecodeSignature())) { return element; } diff --git a/weaver/src/main/java/org/aspectj/weaver/reflect/Java15AnnotationFinder.java b/weaver/src/main/java/org/aspectj/weaver/reflect/Java15AnnotationFinder.java index 016becf87..842863ae3 100644 --- a/weaver/src/main/java/org/aspectj/weaver/reflect/Java15AnnotationFinder.java +++ b/weaver/src/main/java/org/aspectj/weaver/reflect/Java15AnnotationFinder.java @@ -149,9 +149,9 @@ public class Java15AnnotationFinder implements AnnotationFinder, ArgNameFinder { if (anns == null) anns = new org.aspectj.apache.bcel.classfile.annotation.AnnotationGen[0]; // convert to our Annotation type - for (int i = 0; i < anns.length; i++) { - if (anns[i].getTypeSignature().equals(ofType.getSignature())) { - return new BcelAnnotation(anns[i], world); + for (org.aspectj.apache.bcel.classfile.annotation.AnnotationGen ann : anns) { + if (ann.getTypeSignature().equals(ofType.getSignature())) { + return new BcelAnnotation(ann, world); } } return null; @@ -175,8 +175,7 @@ public class Java15AnnotationFinder implements AnnotationFinder, ArgNameFinder { // onMember.getName()+"' in class '"+jc.getClassName()+"'"); } else { Attribute[] attrs = bcelMethod.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - Attribute attribute = attrs[i]; + for (Attribute attribute : attrs) { if (attribute.getName().equals("AnnotationDefault")) { AnnotationDefault def = (AnnotationDefault) attribute; return def.getElementValue().stringifyValue(); diff --git a/weaver/src/main/java/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java b/weaver/src/main/java/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java index 6b65ed31e..f617f49da 100644 --- a/weaver/src/main/java/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java +++ b/weaver/src/main/java/org/aspectj/weaver/reflect/Java15ReflectionBasedReferenceTypeDelegate.java @@ -108,8 +108,8 @@ public class Java15ReflectionBasedReferenceTypeDelegate extends ReflectionBasedR public boolean hasAnnotation(UnresolvedType ofType) { ResolvedType[] myAnns = getAnnotationTypes(); ResolvedType toLookFor = ofType.resolve(getWorld()); - for (int i = 0; i < myAnns.length; i++) { - if (myAnns[i] == toLookFor) { + for (ResolvedType myAnn : myAnns) { + if (myAnn == toLookFor) { return true; } } @@ -270,8 +270,8 @@ public class Java15ReflectionBasedReferenceTypeDelegate extends ReflectionBasedR parser = new InternalUseOnlyPointcutParser(classLoaderReference.getClassLoader()); } Set additionalPointcutHandlers = world.getRegisteredPointcutHandlers(); - for (Iterator handlerIterator = additionalPointcutHandlers.iterator(); handlerIterator.hasNext();) { - PointcutDesignatorHandler handler = (PointcutDesignatorHandler) handlerIterator.next(); + for (Object additionalPointcutHandler : additionalPointcutHandlers) { + PointcutDesignatorHandler handler = (PointcutDesignatorHandler) additionalPointcutHandler; parser.registerPointcutDesignatorHandler(handler); } diff --git a/weaver/src/main/java/org/aspectj/weaver/tools/Jdk14Trace.java b/weaver/src/main/java/org/aspectj/weaver/tools/Jdk14Trace.java index 061b0b0a0..4fc7a1087 100644 --- a/weaver/src/main/java/org/aspectj/weaver/tools/Jdk14Trace.java +++ b/weaver/src/main/java/org/aspectj/weaver/tools/Jdk14Trace.java @@ -84,8 +84,7 @@ public class Jdk14Trace extends AbstractTrace { Logger parent = logger.getParent(); if (parent != null) handlers = parent.getHandlers(); } - for (int i = 0; i < handlers.length; i++) { - Handler handler = handlers[i]; + for (Handler handler : handlers) { handler.setLevel(Level.FINER); } } diff --git a/weaver/src/main/java/org/aspectj/weaver/tools/WeavingAdaptor.java b/weaver/src/main/java/org/aspectj/weaver/tools/WeavingAdaptor.java index 1c0d6e28d..5bb0fd80d 100644 --- a/weaver/src/main/java/org/aspectj/weaver/tools/WeavingAdaptor.java +++ b/weaver/src/main/java/org/aspectj/weaver/tools/WeavingAdaptor.java @@ -570,8 +570,8 @@ public class WeavingAdaptor implements IMessageContext { private void registerAspectLibraries(List aspectPath) { // System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")"); - for (Iterator i = aspectPath.iterator(); i.hasNext();) { - String libName = (String) i.next(); + for (Object o : aspectPath) { + String libName = (String) o; addAspectLibrary(libName); } diff --git a/weaver/src/main/java/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolver.java b/weaver/src/main/java/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolver.java index 4951923d3..44728d041 100644 --- a/weaver/src/main/java/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolver.java +++ b/weaver/src/main/java/org/aspectj/weaver/tools/cache/DefaultCacheKeyResolver.java @@ -55,15 +55,14 @@ public class DefaultCacheKeyResolver implements CacheKeyResolver { // Add the list of loader urls to the hash list if (cl != null && cl instanceof URLClassLoader) { URL[] urls = ((URLClassLoader) cl).getURLs(); - for (int i = 0; i < urls.length; i++) { - hashableStrings.add(urls[i].toString()); + for (URL url : urls) { + hashableStrings.add(url.toString()); } } hashableStrings.addAll(aspects); Collections.sort(hashableStrings); - for (Iterator<String> it = hashableStrings.iterator(); it.hasNext(); ) { - String url = it.next(); + for (String url : hashableStrings) { hashable.append(url); } String hash = null; diff --git a/weaver/src/test/java/org/aspectj/weaver/GenericSignatureParserTest.java b/weaver/src/test/java/org/aspectj/weaver/GenericSignatureParserTest.java index 433eb2c1f..a328a3464 100644 --- a/weaver/src/test/java/org/aspectj/weaver/GenericSignatureParserTest.java +++ b/weaver/src/test/java/org/aspectj/weaver/GenericSignatureParserTest.java @@ -36,8 +36,8 @@ public class GenericSignatureParserTest extends TestCase { "java.lang.InheritableThreadLocal", "java.lang.ThreadLocal", "java.util.Collection", "java.util.Comparator", "java.util.Enumeration", "java.util.Iterator", "java.util.List", "java.util.ListIterator", "java.util.Map", "java.util.Map$Entry", "java.util.Queue", "java.util.Set", "java.util.SortedMap", "java.util.SortedSet" }; - for (int i = 0; i < testClasses.length; i++) { - JavaClass jc = repository.loadClass(testClasses[i]); + for (String testClass : testClasses) { + JavaClass jc = repository.loadClass(testClass); String sig = jc.getGenericSignature(); parser.parseAsClassSignature(sig); } @@ -49,11 +49,11 @@ public class GenericSignatureParserTest extends TestCase { "java.lang.InheritableThreadLocal", "java.lang.ThreadLocal", "java.util.Collection", "java.util.Comparator", "java.util.Enumeration", "java.util.Iterator", "java.util.List", "java.util.ListIterator", "java.util.Map", "java.util.Map$Entry", "java.util.Queue", "java.util.Set", "java.util.SortedMap", "java.util.SortedSet" }; - for (int i = 0; i < testClasses.length; i++) { - JavaClass jc = repository.loadClass(testClasses[i]); + for (String testClass : testClasses) { + JavaClass jc = repository.loadClass(testClass); Method[] methods = jc.getMethods(); - for (int j = 0; j < methods.length; j++) { - String sig = methods[j].getGenericSignature(); + for (Method method : methods) { + String sig = method.getGenericSignature(); if (sig != null) parser.parseAsMethodSignature(sig); } diff --git a/weaver/src/test/java/org/aspectj/weaver/Member15Test.java b/weaver/src/test/java/org/aspectj/weaver/Member15Test.java index 6cb0ce83f..66980f612 100644 --- a/weaver/src/test/java/org/aspectj/weaver/Member15Test.java +++ b/weaver/src/test/java/org/aspectj/weaver/Member15Test.java @@ -26,12 +26,12 @@ public class Member15Test extends TestCase { ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java/lang/Class")); ResolvedMember[] methods = javaLangClass.getDeclaredMethods(); ResolvedMember getAnnotations = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("getAnnotations")) { - getAnnotations = methods[i]; - break; - } - } + for (ResolvedMember method : methods) { + if (method.getName().equals("getAnnotations")) { + getAnnotations = method; + break; + } + } if (getAnnotations != null) { // so can run on non-Java 5 // System.out.println("got it"); assertFalse(getAnnotations.canBeParameterized()); @@ -46,9 +46,9 @@ public class Member15Test extends TestCase { if (javaLangClass == null) return; // for < 1.5 ResolvedMember[] methods = javaLangClass.getDeclaredMethods(); ResolvedMember asSubclass = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("asSubclass")) { - asSubclass = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("asSubclass")) { + asSubclass = method; break; } } @@ -66,9 +66,9 @@ public class Member15Test extends TestCase { if (javaUtilList == null) return; // for < 1.5 ResolvedMember[] methods = javaUtilList.getDeclaredMethods(); ResolvedMember add = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("add")) { - add = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("add")) { + add = method; break; } } diff --git a/weaver/src/test/java/org/aspectj/weaver/Member15TestCase.java b/weaver/src/test/java/org/aspectj/weaver/Member15TestCase.java index 3b37d5ba8..08569f181 100644 --- a/weaver/src/test/java/org/aspectj/weaver/Member15TestCase.java +++ b/weaver/src/test/java/org/aspectj/weaver/Member15TestCase.java @@ -26,12 +26,12 @@ public class Member15TestCase extends TestCase { ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java/lang/Class")); ResolvedMember[] methods = javaLangClass.getDeclaredMethods(); ResolvedMember getAnnotations = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("getAnnotations")) { - getAnnotations = methods[i]; - break; - } - } + for (ResolvedMember method : methods) { + if (method.getName().equals("getAnnotations")) { + getAnnotations = method; + break; + } + } if (getAnnotations != null) { // so can run on non-Java 5 // System.out.println("got it"); assertFalse(getAnnotations.canBeParameterized()); @@ -46,9 +46,9 @@ public class Member15TestCase extends TestCase { if (javaLangClass == null) return; // for < 1.5 ResolvedMember[] methods = javaLangClass.getDeclaredMethods(); ResolvedMember asSubclass = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("asSubclass")) { - asSubclass = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("asSubclass")) { + asSubclass = method; break; } } @@ -66,9 +66,9 @@ public class Member15TestCase extends TestCase { if (javaUtilList == null) return; // for < 1.5 ResolvedMember[] methods = javaUtilList.getDeclaredMethods(); ResolvedMember add = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("add")) { - add = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("add")) { + add = method; break; } } diff --git a/weaver/src/test/java/org/aspectj/weaver/ParameterizedReferenceTypeTestCase.java b/weaver/src/test/java/org/aspectj/weaver/ParameterizedReferenceTypeTestCase.java index 8e04d8c53..695980e6f 100644 --- a/weaver/src/test/java/org/aspectj/weaver/ParameterizedReferenceTypeTestCase.java +++ b/weaver/src/test/java/org/aspectj/weaver/ParameterizedReferenceTypeTestCase.java @@ -33,10 +33,10 @@ public class ParameterizedReferenceTypeTestCase extends TestCase { public void testDeclaredMethodWithParameter() { ResolvedMember[] methods = listOfString.getDeclaredMethods(); ResolvedMember add = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("add")) { - if (methods[i].getParameterTypes().length == 1) { - add = methods[i]; + for (ResolvedMember resolvedMember : methods) { + if (resolvedMember.getName().equals("add")) { + if (resolvedMember.getParameterTypes().length == 1) { + add = resolvedMember; System.out.println(add); // j8: boolean java.util.List<java.lang.String>.add(java.lang.Object) // break; @@ -47,10 +47,10 @@ public class ParameterizedReferenceTypeTestCase extends TestCase { assertEquals("Ljava/lang/String;",parameterType.getSignature()); ResolvedMember get = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("get")) { - if (methods[i].getParameterTypes().length == 1) { - get = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("get")) { + if (method.getParameterTypes().length == 1) { + get = method; break; } } @@ -63,9 +63,9 @@ public class ParameterizedReferenceTypeTestCase extends TestCase { public void testDeclaredMethodWithParameterizedReturnType() { ResolvedMember[] methods = listOfString.getDeclaredMethods(); ResolvedMember iterator = null; - for (int i = 0; i < methods.length; i++) { - if (methods[i].getName().equals("iterator")) { - iterator = methods[i]; + for (ResolvedMember method : methods) { + if (method.getName().equals("iterator")) { + iterator = method; break; } } diff --git a/weaver/src/test/java/org/aspectj/weaver/WeaverMessagesTestCase.java b/weaver/src/test/java/org/aspectj/weaver/WeaverMessagesTestCase.java index 7326971d3..eddcd146d 100644 --- a/weaver/src/test/java/org/aspectj/weaver/WeaverMessagesTestCase.java +++ b/weaver/src/test/java/org/aspectj/weaver/WeaverMessagesTestCase.java @@ -27,17 +27,16 @@ public class WeaverMessagesTestCase extends TestCase { Class<?> wmClass = WeaverMessages.class; Field[] fields = wmClass.getDeclaredFields(); List<String> fieldList = new ArrayList<String>(); - for (int i = 0; i < fields.length; i++) { - Field f = fields[i]; + for (Field f : fields) { if (f.getType() == String.class) { try { String key = (String) f.get(null); // String value = WeaverMessages.format(key); - assertFalse("Each key should be unique",fieldList.contains(key)); + assertFalse("Each key should be unique", fieldList.contains(key)); fieldList.add(key); // System.out.println(key + "," + value); - } catch (IllegalAccessException ex) { - } catch(MissingResourceException mrEx) { + } catch (IllegalAccessException ex) { + } catch (MissingResourceException mrEx) { fail("Missing resource: " + mrEx); } } diff --git a/weaver/src/test/java/org/aspectj/weaver/bcel/ClassLoaderRepositoryTest.java b/weaver/src/test/java/org/aspectj/weaver/bcel/ClassLoaderRepositoryTest.java index a65a25c54..42c5189a4 100644 --- a/weaver/src/test/java/org/aspectj/weaver/bcel/ClassLoaderRepositoryTest.java +++ b/weaver/src/test/java/org/aspectj/weaver/bcel/ClassLoaderRepositoryTest.java @@ -100,10 +100,10 @@ public class ClassLoaderRepositoryTest extends TestCase { threads[i] = new TestThread((i%3)*1000); threads[i].start(); } - for (int i=0; i<threads.length; i++) { - threads[i].join(); - if (threads[i].getFailure() != null) { - throw threads[i].getFailure(); + for (TestThread thread : threads) { + thread.join(); + if (thread.getFailure() != null) { + throw thread.getFailure(); } } } diff --git a/weaver/src/test/java/org/aspectj/weaver/bcel/WeaveTestCase.java b/weaver/src/test/java/org/aspectj/weaver/bcel/WeaveTestCase.java index d336b580c..6e69e2c0f 100644 --- a/weaver/src/test/java/org/aspectj/weaver/bcel/WeaveTestCase.java +++ b/weaver/src/test/java/org/aspectj/weaver/bcel/WeaveTestCase.java @@ -277,15 +277,13 @@ public abstract class WeaveTestCase extends TestCase { // ---- protected void weaveTest(String[] inClassNames, String outKind, ShadowMunger patternMunger) throws IOException { - for (int i = 0; i < inClassNames.length; i++) { - String inFileName = inClassNames[i]; + for (String inFileName : inClassNames) { weaveTest(inFileName, outKind + inFileName, patternMunger); } } protected void weaveTest(String[] inClassNames, String outKind, List<ShadowMunger> patternMungers) throws IOException { - for (int i = 0; i < inClassNames.length; i++) { - String inFileName = inClassNames[i]; + for (String inFileName : inClassNames) { weaveTest(inFileName, outKind + inFileName, patternMungers); } } @@ -300,17 +298,18 @@ public abstract class WeaveTestCase extends TestCase { // XXX cut-and-paster from IdWeaveTestCase public void checkShadowSet(List l, String[] ss) { - outer: for (int i = 0, len = ss.length; i < len; i++) { + outer: + for (String s : ss) { // inner: - for (Iterator j = l.iterator(); j.hasNext();) { + for (Iterator j = l.iterator(); j.hasNext(); ) { BcelShadow shadow = (BcelShadow) j.next(); String shadowString = shadow.toString(); - if (shadowString.equals(ss[i])) { + if (shadowString.equals(s)) { j.remove(); continue outer; } } - assertTrue("didn't find " + ss[i] + " in " + l, false); + assertTrue("didn't find " + s + " in " + l, false); } assertTrue("too many things in " + l, l.size() == 0); } diff --git a/weaver/src/test/java/org/aspectj/weaver/patterns/AnnotationPatternTestCase.java b/weaver/src/test/java/org/aspectj/weaver/patterns/AnnotationPatternTestCase.java index fdf8d5424..0433846fb 100644 --- a/weaver/src/test/java/org/aspectj/weaver/patterns/AnnotationPatternTestCase.java +++ b/weaver/src/test/java/org/aspectj/weaver/patterns/AnnotationPatternTestCase.java @@ -355,8 +355,8 @@ public class AnnotationPatternTestCase extends TestCase { } public boolean hasAnnotation(UnresolvedType ofType) { - for (int i = 0; i < annotationTypes.length; i++) { - if (annotationTypes[i].equals(ofType.getName())) { + for (String annotationType : annotationTypes) { + if (annotationType.equals(ofType.getName())) { return true; } } diff --git a/weaver/src/test/java/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java b/weaver/src/test/java/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java index a0465b34a..9aa4c5a80 100644 --- a/weaver/src/test/java/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java +++ b/weaver/src/test/java/org/aspectj/weaver/reflect/ReflectionBasedReferenceTypeDelegateTest.java @@ -257,23 +257,23 @@ public abstract class ReflectionBasedReferenceTypeDelegateTest extends TestCase ResolvedMember[] rms2 = rawReflectType.getDelegate().getDeclaredMethods(); StringBuffer errors = new StringBuffer(); Set one = new HashSet(); - for (int i = 0; i < rms1.length; i++) { - one.add(rms1[i].toString()); + for (ResolvedMember item : rms1) { + one.add(item.toString()); } Set two = new HashSet(); - for (int i = 0; i < rms2.length; i++) { - two.add(rms2[i].toString()); + for (ResolvedMember value : rms2) { + two.add(value.toString()); } - for (int i = 0; i < rms2.length; i++) { - if (!one.contains(rms2[i].toString())) { - errors.append("Couldn't find " + rms2[i].toString() + " in the bcel set\n"); + for (ResolvedMember member : rms2) { + if (!one.contains(member.toString())) { + errors.append("Couldn't find " + member.toString() + " in the bcel set\n"); } } - for (int i = 0; i < rms1.length; i++) { - if (!two.contains(rms1[i].toString())) { - if (!barfIfClinitMissing && rms1[i].getName().equals("<clinit>")) + for (ResolvedMember resolvedMember : rms1) { + if (!two.contains(resolvedMember.toString())) { + if (!barfIfClinitMissing && resolvedMember.getName().equals("<clinit>")) continue; - errors.append("Couldn't find " + rms1[i].toString() + " in the reflection set\n"); + errors.append("Couldn't find " + resolvedMember.toString() + " in the reflection set\n"); } } assertTrue("Errors:" + errors.toString(), errors.length() == 0); diff --git a/weaver/src/test/java/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java b/weaver/src/test/java/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java index e1a140803..f65053f7e 100644 --- a/weaver/src/test/java/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java +++ b/weaver/src/test/java/org/aspectj/weaver/tools/Java15PointcutExpressionTest.java @@ -298,10 +298,9 @@ public class Java15PointcutExpressionTest extends TestCase { } if (expected.size()>0) { // we have excess ones! StringBuffer excessTokens = new StringBuffer(); - for (Iterator iterator = expected.iterator(); iterator.hasNext();) { - String string = (String) iterator.next(); - excessTokens.append(string).append(" "); - } + for (String string : expected) { + excessTokens.append(string).append(" "); + } fail("In pointcut expression "+pe.getPointcutExpression()+" parameter "+parameterNumber+". The annotation type pattern has these unexpected parameter type annotations "+excessTokens.toString()); } @@ -318,10 +317,9 @@ public class Java15PointcutExpressionTest extends TestCase { } if (expected.size()>0) { // we have excess ones! StringBuffer excessTokens = new StringBuffer(); - for (Iterator iterator = expected.iterator(); iterator.hasNext();) { - String string = (String) iterator.next(); - excessTokens.append(string).append(" "); - } + for (String string : expected) { + excessTokens.append(string).append(" "); + } fail("In pointcut expression "+pe.getPointcutExpression()+" parameter "+parameterNumber+". The annotation type pattern has these unexpected parameter annotations "+excessTokens.toString()); } diff --git a/weaver/src/test/java/org/aspectj/weaver/tools/ReadingAttributesTest.java b/weaver/src/test/java/org/aspectj/weaver/tools/ReadingAttributesTest.java index 11f74ebc1..25dc54009 100644 --- a/weaver/src/test/java/org/aspectj/weaver/tools/ReadingAttributesTest.java +++ b/weaver/src/test/java/org/aspectj/weaver/tools/ReadingAttributesTest.java @@ -34,10 +34,10 @@ public class ReadingAttributesTest extends TestCase { JavaClass jc = getClassFrom(new File("n:/temp"), "com.springsource.petclinic.domain.Visit"); assertNotNull(jc); Attribute[] attrs = jc.getAttributes(); - for (int i = 0; i < attrs.length; i++) { - System.out.println(attrs[i].getName()); - if (attrs[i].getName().endsWith("WeaverState")) { - Unknown u = (Unknown) attrs[i]; + for (Attribute attr : attrs) { + System.out.println(attr.getName()); + if (attr.getName().endsWith("WeaverState")) { + Unknown u = (Unknown) attr; VersionedDataInputStream vdis = new VersionedDataInputStream(new ByteArrayInputStream(u.getBytes()), null); // WeaverStateInfo wsi = WeaverStateInfo.read(vdis, null); |