tags:

views:

71

answers:

4

Getting a syntax error at line:

`List<Class> findClasses(File directory)` throws `ClassNotFoundException`...

Not able to figure out why. Here is my code.

import org.apache.tools.ant.Task;
import java.util.*;
import java.io.*;

public class CreateTestPackage extends Task
{
 String allTestsFile = getProject().getProperty("alltestfiles")+ getProject().getProperty("testfile");
 public void execute()
 {
  List<Class> findClasses(File directory) throws ClassNotFoundException
  {

   List<Class> classes = new ArrayList<Class>();
   if (!directory.exists())
   {
    return classes;
   }
   File[] files = directory.listFiles(new FilenameFilter()
   {
    public boolean accept( File dir, String name )
    {
     return name.matches("test.*\\.class");
    }
   });
   for (File file : files)
   {
    if (file.isDirectory())
    {
     assert !file.getName().contains(".");
     classes.addAll(findClasses(file));
    }
    else if (file.getName().endsWith(".class"))
    {
     classes.add(Class.forName(file.getName().substring(0, file.getName().length() - 6)));
    }
   }
   return classes;
  }
  for(Class c : classes)
  {
     string packageName=c.getPackage().getName();
        BufferedWriter out =null;
        try
        {
           out = new BufferedWriter(new FileWriter(testfile));
           out.write(packageName+"\n");         
        }
        catch (IOException e)
        {
          e.printStackTrace();
       }
        finally
        {
          if (out!=null)
           try
           {
              out.close();
           }
           catch (IOException e)
           {
              e.printStackTrace();
           }
       }
  }

 }
}
+4  A: 

You're defining the method findClasses inside the method execute.

Devon_C_Miller
The call is coming from inside the house!
Ben Hoffstein
@Ben, that's from some movie, right?
jjnguy
@Justin, yes it is the twist ending to "When A Stranger Calls". It is necessary to quote this line any time someone emphasizes the word "inside".
Ben Hoffstein
+6  A: 

The problem is that you define the execute() method, and then try to define the findClasses() method inside of that.

That is not legal Java syntax.

You need to close the method body of execute before you can define another method.

jjnguy
+3  A: 

You're trying to declare a method inside another method. Move the definition of the List<Class> findClasses(File directory) method outside the public void execute() method and just call it when you need to.

Bill the Lizard
+1  A: 

It looks like you're trying to define one method inside of another method. public void execute() is your outer method and you are trying to define List findClasses(File directory) throws ClassNotFoundException as a method inside of that.

You can't do that in Java. What you can do instead is pull the findClasses method out to the same level as execute, and then just call it from inside your execute method.

Jeff