Search in sources :

Example 86 with ClassPool

use of javassist.ClassPool in project systemml by apache.

the class GenerateClassesForMLContext method createFunctionOutputClass.

/**
 * Create a class that encapsulates the outputs of a function.
 *
 * @param scriptFilePath
 *            the path to a script file
 * @param fs
 *            a SystemML function statement
 */
public static void createFunctionOutputClass(String scriptFilePath, FunctionStatement fs) {
    try {
        ArrayList<DataIdentifier> oparams = fs.getOutputParams();
        // than encapsulating it in a function output class
        if ((oparams.size() == 0) || (oparams.size() == 1)) {
            return;
        }
        String fullFunctionOutputClassName = getFullFunctionOutputClassName(scriptFilePath, fs);
        System.out.println("Generating Class: " + fullFunctionOutputClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctFuncOut = pool.makeClass(fullFunctionOutputClassName);
        // add fields
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            String fstring = "public " + type + " " + name + ";";
            CtField field = CtField.make(fstring, ctFuncOut);
            ctFuncOut.addField(field);
        }
        // add constructor
        String simpleFuncOutClassName = fullFunctionOutputClassName.substring(fullFunctionOutputClassName.lastIndexOf(".") + 1);
        StringBuilder con = new StringBuilder();
        con.append("public " + simpleFuncOutClassName + "(");
        for (int i = 0; i < oparams.size(); i++) {
            if (i > 0) {
                con.append(", ");
            }
            DataIdentifier oparam = oparams.get(i);
            String type = getParamTypeAsString(oparam);
            String name = oparam.getName();
            con.append(type + " " + name);
        }
        con.append(") {\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            con.append("this." + name + "=" + name + ";\n");
        }
        con.append("}\n");
        String cstring = con.toString();
        CtConstructor ctCon = CtNewConstructor.make(cstring, ctFuncOut);
        ctFuncOut.addConstructor(ctCon);
        // add toString
        StringBuilder s = new StringBuilder();
        s.append("public String toString(){\n");
        s.append("StringBuilder sb = new StringBuilder();\n");
        for (int i = 0; i < oparams.size(); i++) {
            DataIdentifier oparam = oparams.get(i);
            String name = oparam.getName();
            s.append("sb.append(\"" + name + " (" + getSimpleParamTypeAsString(oparam) + "): \" + " + name + " + \"\\n\");\n");
        }
        s.append("String str = sb.toString();\nreturn str;\n");
        s.append("}\n");
        String toStr = s.toString();
        CtMethod toStrMethod = CtNewMethod.make(toStr, ctFuncOut);
        ctFuncOut.addMethod(toStrMethod);
        ctFuncOut.writeFile(destination);
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : DataIdentifier(org.apache.sysml.parser.DataIdentifier) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) IOException(java.io.IOException) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) CtMethod(javassist.CtMethod)

Example 87 with ClassPool

use of javassist.ClassPool in project turbo-rpc by hank-whu.

the class FailoverInvokerFactory method generateDefaultImplObject.

private Object generateDefaultImplObject(Class<?> clazz) throws Exception {
    if (clazz == null) {
        throw new RuntimeException("clazz must not be null");
    }
    Method[] allMethods = clazz.getMethods();
    for (Method method : allMethods) {
        if (!CompletableFuture.class.equals(method.getReturnType())) {
            throw new RuntimeException("method return-type must be CompletableFuture, " + method);
        }
    }
    if (!Stream.of(allMethods).anyMatch(m -> m.isDefault())) {
        return null;
    }
    final String remoteClassName = // 
    clazz.getName() + "_DefaultImpl_" + UUID.randomUUID().toString().replace("-", "");
    // 创建类
    ClassPool pool = ClassPool.getDefault();
    CtClass defaultImplCtClass = pool.makeClass(remoteClassName);
    CtClass[] interfaces = { pool.getCtClass(clazz.getName()) };
    defaultImplCtClass.setInterfaces(interfaces);
    // 添加无参的构造函数
    CtConstructor constructor = new CtConstructor(null, defaultImplCtClass);
    constructor.setModifiers(Modifier.PUBLIC);
    constructor.setBody("{}");
    defaultImplCtClass.addConstructor(constructor);
    for (Method method : allMethods) {
        if (method.isDefault()) {
            continue;
        }
        StringBuilder methodBuilder = new StringBuilder();
        methodBuilder.append("public ");
        methodBuilder.append(method.getReturnType().getName());
        methodBuilder.append(" ");
        methodBuilder.append(method.getName());
        methodBuilder.append("(");
        Class<?>[] parameterTypes = method.getParameterTypes();
        for (int i = 0; i < parameterTypes.length; i++) {
            Class<?> parameterType = parameterTypes[i];
            methodBuilder.append(parameterType.getName());
            methodBuilder.append(" param");
            methodBuilder.append(i);
            if (i != parameterTypes.length - 1) {
                methodBuilder.append(", ");
            }
        }
        methodBuilder.append("){\r\n  throw new UnsupportedOperationException();\r\n}");
        CtMethod m = CtNewMethod.make(methodBuilder.toString(), defaultImplCtClass);
        defaultImplCtClass.addMethod(m);
    }
    Class<?> invokerClass = defaultImplCtClass.toClass();
    return invokerClass.getConstructor().newInstance();
}
Also used : CtMethod(javassist.CtMethod) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CompletableFuture(java.util.concurrent.CompletableFuture) UUID(java.util.UUID) CtClass(javassist.CtClass) ConcurrentMap(java.util.concurrent.ConcurrentMap) CtNewMethod(javassist.CtNewMethod) Stream(java.util.stream.Stream) Modifier(java.lang.reflect.Modifier) CtConstructor(javassist.CtConstructor) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Method(java.lang.reflect.Method) ClassPool(javassist.ClassPool) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) CtNewMethod(javassist.CtNewMethod) Method(java.lang.reflect.Method) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CompletableFuture(java.util.concurrent.CompletableFuture) CtClass(javassist.CtClass) CtMethod(javassist.CtMethod)

Example 88 with ClassPool

use of javassist.ClassPool in project turbo-rpc by hank-whu.

the class MethodParamClassFactory method doCreateClass.

@SuppressWarnings("unchecked")
private static Class<? extends MethodParam> doCreateClass(Method method) throws CannotCompileException, NotFoundException {
    Class<?>[] parameterTypes = method.getParameterTypes();
    Parameter[] parameters = method.getParameters();
    if (!parameters[0].isNamePresent()) {
        throw new RuntimeException(NOT_SUPPORT_PARAMETER_NAME_MSG);
    }
    String paramTypes = // 
    Stream.of(parameterTypes).map(// 
    clazz -> clazz.getName()).collect(Collectors.joining(",", "(", ")"));
    String hash = Hashing.murmur3_128().hashString(paramTypes, StandardCharsets.UTF_8).toString();
    final String methodParamClassName = // 
    method.getDeclaringClass().getName() + // 
    "$MethodParam" + "$" + // 
    method.getName() + "$" + // 
    parameterTypes.length + "$" + // 防止同名方法冲突
    hash;
    try {
        Class<?> clazz = MethodParamClassFactory.class.getClassLoader().loadClass(methodParamClassName);
        if (clazz != null) {
            return (Class<? extends MethodParam>) clazz;
        }
    } catch (ClassNotFoundException e) {
    }
    // 创建类
    ClassPool pool = ClassPool.getDefault();
    CtClass methodParamCtClass = pool.makeClass(methodParamClassName);
    CtClass[] interfaces = { pool.getCtClass(MethodParam.class.getName()) };
    methodParamCtClass.setInterfaces(interfaces);
    for (int i = 0; i < parameterTypes.length; i++) {
        Parameter parameter = parameters[i];
        String paramName = parameter.getName();
        Class<?> paramType = parameterTypes[i];
        String capitalize = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
        String getter = "get" + capitalize;
        String setter = "set" + capitalize;
        CtField ctField = new CtField(pool.get(paramType.getName()), paramName, methodParamCtClass);
        ctField.setModifiers(Modifier.PRIVATE);
        methodParamCtClass.addField(ctField);
        methodParamCtClass.addMethod(CtNewMethod.getter("$param" + i, ctField));
        methodParamCtClass.addMethod(CtNewMethod.getter(getter, ctField));
        methodParamCtClass.addMethod(CtNewMethod.setter(setter, ctField));
    }
    // 添加无参的构造函数
    CtConstructor constructor0 = new CtConstructor(null, methodParamCtClass);
    constructor0.setModifiers(Modifier.PUBLIC);
    constructor0.setBody("{}");
    methodParamCtClass.addConstructor(constructor0);
    // 添加有参的构造函数
    CtClass[] paramCtClassArray = new CtClass[method.getParameterCount()];
    for (int i = 0; i < method.getParameterCount(); i++) {
        Class<?> paramType = parameterTypes[i];
        CtClass paramCtClass = pool.get(paramType.getName());
        paramCtClassArray[i] = paramCtClass;
    }
    StringBuilder bodyBuilder = ThreadLocalStringBuilder.current();
    bodyBuilder.append("{\r\n");
    for (int i = 0; i < method.getParameterCount(); i++) {
        String paramName = parameters[i].getName();
        bodyBuilder.append("$0.");
        bodyBuilder.append(paramName);
        bodyBuilder.append(" = $");
        bodyBuilder.append(i + 1);
        bodyBuilder.append(";\r\n");
    }
    bodyBuilder.append("}");
    CtConstructor constructor1 = new CtConstructor(paramCtClassArray, methodParamCtClass);
    constructor1.setBody(bodyBuilder.toString());
    methodParamCtClass.addConstructor(constructor1);
    return (Class<? extends MethodParam>) methodParamCtClass.toClass();
}
Also used : CannotCompileException(javassist.CannotCompileException) Modifier(javassist.Modifier) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Hashing(com.google.common.hash.Hashing) CtClass(javassist.CtClass) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ConcurrentMap(java.util.concurrent.ConcurrentMap) Objects(java.util.Objects) CtField(javassist.CtField) CtNewMethod(javassist.CtNewMethod) Stream(java.util.stream.Stream) Parameter(java.lang.reflect.Parameter) CtConstructor(javassist.CtConstructor) NotFoundException(javassist.NotFoundException) ThreadLocalStringBuilder(rpc.turbo.util.concurrent.ThreadLocalStringBuilder) Method(java.lang.reflect.Method) ClassPool(javassist.ClassPool) ThreadLocalStringBuilder(rpc.turbo.util.concurrent.ThreadLocalStringBuilder) ClassPool(javassist.ClassPool) CtConstructor(javassist.CtConstructor) CtClass(javassist.CtClass) CtField(javassist.CtField) Parameter(java.lang.reflect.Parameter) CtClass(javassist.CtClass)

Example 89 with ClassPool

use of javassist.ClassPool in project incubator-servicecomb-java-chassis by apache.

the class JavassistUtils method detach.

// for test
public static void detach(String clsName) {
    try {
        ClassPool classPool = getOrCreateClassPool(Thread.currentThread().getContextClassLoader());
        classPool.getCtClass(clsName).detach();
    } catch (NotFoundException e) {
    // do nothing.
    }
}
Also used : ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException)

Example 90 with ClassPool

use of javassist.ClassPool in project incubator-servicecomb-java-chassis by apache.

the class JavassistUtils method createClass.

public static Class<?> createClass(ClassLoader classLoader, ClassConfig config) {
    if (classLoader == null) {
        classLoader = Thread.currentThread().getContextClassLoader();
    }
    ClassPool classPool = getOrCreateClassPool(classLoader);
    CtClass ctClass = classPool.getOrNull(config.getClassName());
    if (ctClass == null) {
        if (config.isIntf()) {
            ctClass = classPool.makeInterface(config.getClassName());
        } else {
            ctClass = classPool.makeClass(config.getClassName());
        }
    }
    try {
        for (String intfName : config.getIntfList()) {
            ctClass.addInterface(classPool.get(intfName));
        }
        for (FieldConfig fieldConfig : config.getFieldList()) {
            CtField field = createCtField(classPool, ctClass, fieldConfig);
            ctClass.addField(field);
            if (fieldConfig.isGenGetter()) {
                addFieldGetter(config, fieldConfig);
            }
            if (fieldConfig.isGenSetter()) {
                addFieldSetter(config, fieldConfig);
            }
        }
        for (MethodConfig methodConfig : config.getMethodList()) {
            try {
                CtMethod ctMethod = CtMethod.make(methodConfig.getSource(), ctClass);
                if (methodConfig.getGenericSignature() != null) {
                    ctMethod.setGenericSignature(methodConfig.getGenericSignature());
                }
                ctClass.addMethod(ctMethod);
            } catch (CannotCompileException e) {
                LOGGER.error("Failed to create method, source:\n{}.", methodConfig.getSource());
                throw e;
            }
        }
        LOGGER.info("generate {} in classLoader {}.", config.getClassName(), classLoader);
        return ctClass.toClass(classLoader, null);
    } catch (Throwable e) {
        throw new Error(String.format("Failed to create %s in classLoader %s.", config.getClassName(), classLoader), e);
    }
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CannotCompileException(javassist.CannotCompileException) CtMethod(javassist.CtMethod)

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