Search in sources :

Example 61 with ClassPool

use of javassist.ClassPool in project jPOS by jpos.

the class Slf4JDynamicBinder method applyMods.

public static void applyMods() throws Exception {
    if (!bound && !bindingsExist()) {
        final ProtectionDomain pd = Slf4JDynamicBinder.class.getProtectionDomain();
        final ClassPool cp = ClassPool.getDefault();
        CtClass clz = cp.getAndRename(StaticLoggerBinder.class.getName(), STATIC_BINDER_CLASS);
        clz.toClass(null, pd);
        CtClass clz2 = cp.get("org.slf4j.LoggerFactory");
        CtMethod bindMethod = clz2.getDeclaredMethod("bind");
        bindMethod.setBody("try " + "{" + " org.slf4j.impl.StaticLoggerBinder.getSingleton();" + " INITIALIZATION_STATE = SUCCESSFUL_INITIALIZATION;" + " fixSubstituteLoggers();" + " replayEvents();" + " SUBST_FACTORY.clear();" + "} " + "catch(Exception e)" + "{" + " failedBinding(e); " + " throw new IllegalStateException(\"Unexpected initialization failure\", e);" + "}");
        clz2.toClass(null, pd);
        clz2.detach();
        clz.detach();
        bound = true;
    }
}
Also used : ProtectionDomain(java.security.ProtectionDomain) CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod)

Example 62 with ClassPool

use of javassist.ClassPool in project dubbo-faker by moyada.

the class VariableUtil method getNameByJavassist.

// /**
// * 通过 ASM 获取属性名
// * @param clazz
// * @param method
// * @return
// * @throws IOException
// */
// public static String[] getNameByASM(Class clazz, Method method) throws IOException {
// final Class<?>[] methodParameterTypes = method.getParameterTypes();
// final int methodParameterCount = methodParameterTypes.length;
// final boolean isStatic = Modifier.isStatic(method.getModifiers());
// 
// // 读取字节码信息到ClassReader中
// ClassReader reader = new ClassReader(clazz.getName());
// ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
// 
// String[] variableName = new String[methodParameterCount];
// 
// reader.accept(new ClassVisitor(cw.hashCode(), cw) {
// /**
// * 会遍历该类的所有方法,你可以对不需要操作的方法直接返回
// */
// @Override
// public MethodVisitor visitMethod(final int access, final String name, final String desc,
// final String signature, final String[] exceptions) {
// 
// MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
// 
// final Type[] argTypes = Type.getArgumentTypes(desc);
// 
// //不需要操作的方法,直接返回,注意不要返回null,会把该方法删掉
// if (!name.equals(method.getName()) || !matchTypes(argTypes, methodParameterTypes)) {
// return mv;
// }
// 
// // 遍历该方法信息
// return new MethodVisitor(mv.hashCode(), mv) {
// 
// @Override
// public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
// //如果是静态方法,第一个参数就是方法参数,非静态方法,则第一个参数是 this ,然后才是方法的参数
// int methodParameterIndex = isStatic ? index : index - 1;
// if (0 <= methodParameterIndex && methodParameterIndex < methodParameterCount) {
// variableName[methodParameterIndex] = name;
// }
// super.visitLocalVariable(name, desc, signature, start, end, index);
// }
// };
// }
// }, 0);
// 
// return variableName;
// }
// 
// /**
// * 比较参数是否一致
// */
// private static boolean matchTypes(Type[] types, Class<?>[] parameterTypes) {
// if (types.length != parameterTypes.length) {
// return false;
// }
// for (int i = 0; i < types.length; i++) {
// if (!Type.getType(parameterTypes[i]).equals(types[i])) {
// return false;
// }
// }
// return true;
// }
/**
 * 通过 javassist 获取属性名
 * @param clazz
 * @param method
 * @return
 * @throws NotFoundException
 */
public static String[] getNameByJavassist(Class clazz, Method method) throws NotFoundException {
    ClassPool classPool = ClassPool.getDefault();
    CtClass ctClass = classPool.get(clazz.getName());
    int count = method.getParameterCount();
    Class<?>[] paramTypes = method.getParameterTypes();
    CtClass[] ctParams = new CtClass[count];
    for (int i = 0; i < count; i++) {
        ctParams[i] = classPool.getCtClass(paramTypes[i].getName());
    }
    CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName(), ctParams);
    // 得到该方法信息类
    MethodInfo methodInfo = ctMethod.getMethodInfo();
    // 获取属性变量相关
    CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
    if (codeAttribute == null) {
        return null;
    }
    // 获取方法本地变量信息,包括方法声明和方法体内的变量
    // 需注意,若方法为非静态方法,则第一个变量名为this
    LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
    String[] variableName = new String[count];
    int index = 0;
    int pos = 0;
    if (!Modifier.isStatic(method.getModifiers())) {
        count++;
        pos++;
    }
    for (int i = pos; i < count; i++) {
        variableName[index++] = attr.variableName(i);
    }
    return variableName;
}
Also used : CtClass(javassist.CtClass) CodeAttribute(javassist.bytecode.CodeAttribute) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) MethodInfo(javassist.bytecode.MethodInfo) LocalVariableAttribute(javassist.bytecode.LocalVariableAttribute) CtMethod(javassist.CtMethod)

Example 63 with ClassPool

use of javassist.ClassPool in project Hystrix by Netflix.

the class NetworkClassTransform method wrapClass.

/**
 * Wrap all signatures of a given method name.
 *
 * @param className
 * @param methodName
 * @throws NotFoundException
 * @throws CannotCompileException
 * @throws IOException
 */
private byte[] wrapClass(String className, boolean wrapConstructors, String... methodNames) throws NotFoundException, IOException, CannotCompileException {
    ClassPool cp = ClassPool.getDefault();
    CtClass ctClazz = cp.get(className);
    // constructors
    if (wrapConstructors) {
        CtConstructor[] constructors = ctClazz.getConstructors();
        for (CtConstructor constructor : constructors) {
            try {
                constructor.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.notifyOfNetworkEvent(); }");
            } catch (Exception e) {
                throw new RuntimeException("Failed trying to wrap constructor of class: " + className, e);
            }
        }
    }
    // methods
    CtMethod[] methods = ctClazz.getDeclaredMethods();
    for (CtMethod method : methods) {
        try {
            for (String methodName : methodNames) {
                if (method.getName().equals(methodName)) {
                    method.insertBefore("{ com.netflix.hystrix.contrib.networkauditor.HystrixNetworkAuditorAgent.handleNetworkEvent(); }");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed trying to wrap method [" + method.getName() + "] of class: " + className, e);
        }
    }
    return ctClazz.toBytecode();
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) IllegalClassFormatException(java.lang.instrument.IllegalClassFormatException) NotFoundException(javassist.NotFoundException) IOException(java.io.IOException) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Example 64 with ClassPool

use of javassist.ClassPool in project hibernate-orm by hibernate.

the class EnhancerImpl method buildClassPool.

private ClassPool buildClassPool(JavassistEnhancementContext enhancementContext) {
    ClassPool classPool = new ClassPool(false) {

        @Override
        public ClassLoader getClassLoader() {
            return enhancementContext.getLoadingClassLoader();
        }
    };
    ClassLoader loadingClassLoader = enhancementContext.getLoadingClassLoader();
    if (loadingClassLoader != null) {
        classPool.appendClassPath(new LoaderClassPath(loadingClassLoader));
    }
    return classPool;
}
Also used : ClassPool(javassist.ClassPool) LoaderClassPath(javassist.LoaderClassPath)

Example 65 with ClassPool

use of javassist.ClassPool in project hibernate-orm by hibernate.

the class EnhancerTestUtils method generateCtClassForAnEntity.

private static CtClass generateCtClassForAnEntity(Class<?> entityClassToEnhance) throws Exception {
    ClassPool cp = new ClassPool(false);
    ClassLoader cl = EnhancerTestUtils.class.getClassLoader();
    return cp.makeClass(cl.getResourceAsStream(entityClassToEnhance.getName().replace('.', '/') + ".class"));
}
Also used : ClassPool(javassist.ClassPool)

Aggregations

ClassPool (javassist.ClassPool)120 CtClass (javassist.CtClass)93 CtMethod (javassist.CtMethod)48 NotFoundException (javassist.NotFoundException)40 CannotCompileException (javassist.CannotCompileException)28 IOException (java.io.IOException)23 LoaderClassPath (javassist.LoaderClassPath)21 CtField (javassist.CtField)20 CtConstructor (javassist.CtConstructor)17 Test (org.junit.Test)17 ClassFile (javassist.bytecode.ClassFile)15 File (java.io.File)13 Method (java.lang.reflect.Method)13 ByteArrayInputStream (java.io.ByteArrayInputStream)12 ConstPool (javassist.bytecode.ConstPool)12 FileNotFoundException (java.io.FileNotFoundException)11 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)9 AnnotationsAttribute (javassist.bytecode.AnnotationsAttribute)9 ClassClassPath (javassist.ClassClassPath)7 MethodInfo (javassist.bytecode.MethodInfo)7