// verify pattern and add compiled pattern to static cache private void initPatterns(MethodVisitor mv) { mv.visitIntInsn(BIPUSH, myPatterns.size()); mv.visitTypeInsn(ANEWARRAY, "java/util/regex/Pattern"); mv.visitFieldInsn(PUTSTATIC, myClassName, PATTERN_CACHE_NAME, JAVA_UTIL_REGEX_PATTERN); int i = 0; for (String pattern : myPatterns) { // check the pattern so we can rely on the pattern being valid at runtime try { Pattern.compile(pattern); } catch (Exception e) { throw new InstrumentationException("Illegal Pattern: " + pattern, e); } mv.visitFieldInsn(GETSTATIC, myClassName, PATTERN_CACHE_NAME, JAVA_UTIL_REGEX_PATTERN); mv.visitIntInsn(BIPUSH, i++); mv.visitLdcInsn(pattern); mv.visitMethodInsn( INVOKESTATIC, "java/util/regex/Pattern", "compile", "(Ljava/lang/String;)Ljava/util/regex/Pattern;", false); mv.visitInsn(AASTORE); } }
// add assert startup code private void initAssertions(MethodVisitor mv) { mv.visitLdcInsn(Type.getType("L" + myClassName + ";")); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Class", "desiredAssertionStatus", "()Z", false); Label l0 = new Label(); mv.visitJumpInsn(IFNE, l0); mv.visitInsn(ICONST_1); Label l1 = new Label(); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l0); mv.visitInsn(ICONST_0); mv.visitLabel(l1); mv.visitFieldInsn(PUTSTATIC, myClassName, ASSERTIONS_DISABLED_NAME, "Z"); }