views:

44

answers:

2

I use Eclipse Galileo to develop Java code. When implementing an interface for mocking, I often want to specify the behavior of just a few methods and retain the default behavior (do nothing or return null/0) for most. Eclipse will produce a nicely formatted default implementation like:

    HttpServletRequest mock = new HttpServletRequest() {

        public String getQueryString() {
            return "foobar";
        }

        public void setAttribute(String arg0, Object arg1) {
            // TODO Auto-generated method stub

        }

        public int getServerPort() {
            // TODO Auto-generated method stub
            return 0;
        }

        public String getServerName() {
            // TODO Auto-generated method stub
            return null;
        }

        ... etc, etc, etc ...           

For legibilty and cleanliness I'm looking for a regexp (for Eclipse's find/replace dialog) to clean this up, which will produce the following result when run on the above code:

    HttpServletRequest mock = new HttpServletRequest() {

        public String getQueryString() {
            return "foobar";
        }

        public void setAttribute(String arg0, Object arg1) {}
        public int getServerPort() {return 0;}          
        public String getServerName() {return null;}

        ... etc...          

Basically:

  • remove any char/new line/tab between { and }

  • but keep and rewrite "return (.*);" if there is such a thing (void methods don't have the return statement)

It's OK to hand check each replace and skip the ones I want to keep (need not be fully automated)

A: 

I came up with something like:

  • Find pattern: (public|private|protected)\s+(\w+)\s+(\w+)(\(.*\))\s+\{\s*(// TODO Auto-generated method stub)\s*(.*)\s*\}
  • Replace pattern: $1 $2 $3$4 { $6 }
Lorenzo V.
Thanks you put me on track: here's my final solution. Find: (ublic|rivate|rotected)(.*)\{[\s\S]*?(return \w+;)?\s*?\}\s+(^\s*\w) Replace: $1$2{$3}\R$4
Philipp
A: 

See how this is done with Adapters in swing, where the adapter is a dummy implementation of a given interface, and you then override just what you need. Gives very concise code even with anonynous classes.

Thorbjørn Ravn Andersen
Good suggestion, although I normally use EasyMock to do this. It's even better than an adapter class, but cannot be used in a 1.4 JVM environment. (my case here)
Philipp
EasyMock? Hmmm... I wouldn't. But anyway, have you considered cleaning the Eclipse templates used to generate the code? You can make it generate just about anything (but your {}'s will not survive an Eclipse source formatter run)
Thorbjørn Ravn Andersen