开发者

Regexp to compact default method implementations in Eclipse

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";
     开发者_如何学Python   }

        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)


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 }


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜