Shouldn't “static” patterns always be static?

前端 未结 5 1530
名媛妹妹
名媛妹妹 2021-01-01 10:42

I just found a bug in some code I didn\'t write and I\'m a bit surprised:

Pattern pattern = Pattern.compile(\"\\\\d{1,2}.\\\\d{1,2}.\\\\d{4}\");
Matcher matc         


        
5条回答
  •  耶瑟儿~
    2021-01-01 11:11

    1. Yes, the whole point of pre-compiling a Pattern is to only do it once.
    2. It really depends on how you're going to use it, but in general, pre-compiled patterns stored in static fields should be fine. (Unlike Matchers, which aren't threadsafe and therefore shouldn't really be stored in fields at all, static or not.)

    The only caveat with compiling patterns in static initializers is that if the pattern doesn't compile and the static initializer throws an exception, the source of the error can be quite annoying to track down. It's a minor maintainability problem but it might be worth mentioning.

提交回复
热议问题