// 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"); }
/** * Visits a LDC instruction. Note that new constant types may be added in future versions of the * Java Virtual Machine. To easily detect new constant types, implementations of this method * should check for unexpected constant types, like this: * * <pre> * if (cst instanceof Integer) { * // ... * } else if (cst instanceof Float) { * // ... * } else if (cst instanceof Long) { * // ... * } else if (cst instanceof Double) { * // ... * } else if (cst instanceof String) { * // ... * } else if (cst instanceof Type) { * int sort = ((Type) cst).getSort(); * if (sort == Type.OBJECT) { * // ... * } else if (sort == Type.ARRAY) { * // ... * } else if (sort == Type.METHOD) { * // ... * } else { * // throw an exception * } * } else if (cst instanceof Handle) { * // ... * } else { * // throw an exception * } * </pre> * * @param cst the constant to be loaded on the stack. This parameter must be a non null {@link * Integer}, a {@link Float}, a {@link Long}, a {@link Double}, a {@link String}, a {@link * Type} of OBJECT or ARRAY sort for <tt>.class</tt> constants, for classes whose version is * 49.0, a {@link Type} of METHOD sort or a {@link Handle} for MethodType and MethodHandle * constants, for classes whose version is 51.0. */ public void visitLdcInsn(Object cst) { if (mv != null) { mv.visitLdcInsn(cst); } }