nobody
nobody

Reputation: 1949

Automating deleting lines of code from .java file, script

As part of code cleanup, and migrating to new test framework, I need to delete constructor which has argument 'String name' from all the test classes(Almost 1000+ *.java files). For example , the part shown in comment need to be deleted.

class A extends TestCase{
   //This need to be deleted.
   public A(String name){
      super(name);
   }
   // End of part to be deleted

}

Is there any way to automate this using ant script or using java itself?

Upvotes: 0

Views: 245

Answers (2)

limc
limc

Reputation: 40176

I supposed you can read all the Java files from a directory, and for each Java file, read it into a String, then use regexp to remove the constructor... something like this?

    Pattern p = Pattern.compile("class (\\w+) extends TestCase");
    Matcher m = p.matcher(javaSourceCode);

    String className = "";
    if (m.find()) {
        className = m.group(1);
    }

    String out =  javaSourceCode.replaceFirst("public "+className+"\\s*\\(String name\\)\\s*\\n*\\{[\\w\\W]*?\\}", "");

    System.out.println(out);

Upvotes: 3

Stephen C
Stephen C

Reputation: 719239

It the pattern is tightly constrained, I'd use sed or perl for a task like this.

But I'd also consider just leaving the redundant constructors alone. They don't do much harm, especially if they are all in unit tests.

Upvotes: 0

Related Questions