Search in sources :

Example 21 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class XStreamClassloaderExecutorTest method createClassloader.

private MockClassLoader createClassloader() {
    MockClassLoader classloader = new MockClassLoader(new String[] { MyClass.class.getName(), MyArgument.class.getName(), MyReturnValue.class.getName() });
    MockTransformer mainMockTransformer = new MockTransformer() {

        public CtClass transform(CtClass clazz) throws Exception {
            return clazz;
        }
    };
    LinkedList<MockTransformer> linkedList = new LinkedList<MockTransformer>();
    linkedList.add(mainMockTransformer);
    classloader.setMockTransformerChain(linkedList);
    return classloader;
}
Also used : MyClass(powermock.classloading.classes.MyClass) MyArgument(powermock.classloading.classes.MyArgument) MockTransformer(org.powermock.core.transformers.MockTransformer) CtClass(javassist.CtClass) MockClassLoader(org.powermock.core.classloader.MockClassLoader) MyReturnValue(powermock.classloading.classes.MyReturnValue) LinkedList(java.util.LinkedList)

Example 22 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class MockClassLoader method loadMockClass.

/**
     * Load a mocked version of the class.
     */
private Class<?> loadMockClass(String name, ProtectionDomain protectionDomain) {
    final byte[] clazz;
    ClassPool.doPruning = false;
    try {
        CtClass type = classPool.get(name);
        for (MockTransformer transformer : mockTransformerChain) {
            type = transformer.transform(type);
        }
        javaAssistClassMarker.mark(type);
        /*
             * ClassPool may cause huge memory consumption if the number of CtClass
             * objects becomes amazingly large (this rarely happens since Javassist
             * tries to reduce memory consumption in various ways). To avoid this
             * problem, you can explicitly remove an unnecessary CtClass object from
             * the ClassPool. If you call detach() on a CtClass object, then that
             * CtClass object is removed from the ClassPool.
             */
        type.detach();
        clazz = type.toBytecode();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to transform class with name " + name + ". Reason: " + e.getMessage(), e);
    }
    return defineClass(name, clazz, 0, clazz.length, protectionDomain);
}
Also used : MockTransformer(org.powermock.core.transformers.MockTransformer) CtClass(javassist.CtClass)

Example 23 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class AbstractMainMockTransformer method modifyMethod.

private void modifyMethod(final CtMethod method) throws NotFoundException, CannotCompileException {
    if (!shouldSkipMethod(method)) {
        // Lookup the method return type
        final CtClass returnTypeAsCtClass = method.getReturnType();
        final String returnTypeAsString = getReturnTypeAsString(method);
        if (Modifier.isNative(method.getModifiers())) {
            modifyNativeMethod(method, returnTypeAsCtClass, returnTypeAsString);
        } else {
            modifyMethod(method, returnTypeAsCtClass, returnTypeAsString);
        }
    }
}
Also used : CtClass(javassist.CtClass)

Example 24 with CtClass

use of javassist.CtClass in project powermock by powermock.

the class PowerMockClassTransformer method transform.

public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
    if (loader == null || shouldIgnore(className)) {
        return null;
    }
    try {
        String normalizedClassName = className.replace("/", ".");
        if (classesToTransform != null && classesToTransform.contains(normalizedClassName)) {
            ByteArrayInputStream is = new ByteArrayInputStream(classfileBuffer);
            CtClass ctClass = null;
            try {
                ctClass = ClassPool.getDefault().makeClass(is);
            } finally {
                is.close();
            }
            if (ctClass.isInterface()) {
                ctClass = INTERFACE_MOCK_TRANSFORMER.transform(ctClass);
            } else {
                ctClass = CLASS_MOCK_TRANSFORMER.transform(ctClass);
            }
            /*
                 * ClassPool may cause huge memory consumption if the number of CtClass
                 * objects becomes amazingly large (this rarely happens since Javassist
                 * tries to reduce memory consumption in various ways). To avoid this
                 * problem, you can explicitly remove an unnecessary CtClass object from
                 * the ClassPool. If you call detach() on a CtClass object, then that
                 * CtClass object is removed from the ClassPool.
                 */
            ctClass.detach();
            javaAgentClassRegister.registerClass(loader, normalizedClassName);
            return ctClass.toBytecode();
        }
        return null;
    } catch (Exception e) {
        throw new RuntimeException("Failed to redefine class " + className, e);
    }
}
Also used : CtClass(javassist.CtClass) ByteArrayInputStream(java.io.ByteArrayInputStream) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException)

Example 25 with CtClass

use of javassist.CtClass in project ratpack by ratpack.

the class DescribingHandlers method describeTo.

public static void describeTo(Handler handler, StringBuilder stringBuilder) {
    Class<? extends Handler> clazz = handler.getClass();
    if (clazz.isAnonymousClass()) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass;
        try {
            ctClass = pool.get(clazz.getName());
            CtBehavior[] behaviors = ctClass.getDeclaredBehaviors();
            List<CtBehavior> withLineNumber = Arrays.asList(behaviors).stream().filter(input -> input.getMethodInfo().getLineNumber(0) > 0).sorted((o1, o2) -> Integer.valueOf(o1.getMethodInfo().getLineNumber(0)).compareTo(o2.getMethodInfo().getLineNumber(0))).collect(Collectors.toList());
            if (!withLineNumber.isEmpty()) {
                CtBehavior method = withLineNumber.get(0);
                int lineNumber = method.getMethodInfo().getLineNumber(0);
                ClassFile classFile = ctClass.getClassFile();
                String sourceFile = classFile.getSourceFile();
                if (lineNumber != -1 && sourceFile != null) {
                    stringBuilder.append("anonymous class ").append(clazz.getName()).append(" at approximately line ").append(lineNumber).append(" of ").append(sourceFile);
                    return;
                }
            }
        } catch (NotFoundException ignore) {
        // fall through
        }
    }
    stringBuilder.append(clazz.getName());
}
Also used : CtBehavior(javassist.CtBehavior) Arrays(java.util.Arrays) List(java.util.List) ClassFile(javassist.bytecode.ClassFile) Handler(ratpack.handling.Handler) NotFoundException(javassist.NotFoundException) CtBehavior(javassist.CtBehavior) CtClass(javassist.CtClass) Collectors(java.util.stream.Collectors) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) ClassFile(javassist.bytecode.ClassFile) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException)

Aggregations

CtClass (javassist.CtClass)113 CtMethod (javassist.CtMethod)42 NotFoundException (javassist.NotFoundException)33 ClassPool (javassist.ClassPool)32 Test (org.junit.Test)32 CannotCompileException (javassist.CannotCompileException)22 CtField (javassist.CtField)20 IOException (java.io.IOException)10 CtConstructor (javassist.CtConstructor)8 Method (java.lang.reflect.Method)7 ArrayList (java.util.ArrayList)6 CtMethodJavaWriter (com.github.stephanenicolas.afterburner.inserts.CtMethodJavaWriter)4 FileNotFoundException (java.io.FileNotFoundException)4 LoaderClassPath (javassist.LoaderClassPath)4 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)4 CodeAttribute (javassist.bytecode.CodeAttribute)4 ConstPool (javassist.bytecode.ConstPool)4 GwtTestPatchException (com.googlecode.gwt.test.exceptions.GwtTestPatchException)3 PinpointException (com.navercorp.pinpoint.exception.PinpointException)3 NamedClassPool (com.navercorp.pinpoint.profiler.instrument.classpool.NamedClassPool)3