Search in sources :

Example 51 with CtConstructor

use of javassist.CtConstructor in project powermock by powermock.

the class TestClassTransformer method restoreOriginalConstructorsAccesses.

private void restoreOriginalConstructorsAccesses(CtClass clazz) throws Exception {
    Class<?> originalClass = testClass.getName().equals(clazz.getName()) ? testClass : Class.forName(clazz.getName(), true, testClass.getClassLoader());
    for (final CtConstructor ctConstr : clazz.getConstructors()) {
        int ctModifiers = ctConstr.getModifiers();
        if (!Modifier.isPublic(ctModifiers)) {
            /* Probably a defer-constructor */
            continue;
        }
        int desiredAccessModifiers = originalClass.getDeclaredConstructor(asOriginalClassParams(ctConstr.getParameterTypes())).getModifiers();
        if (Modifier.isPrivate(desiredAccessModifiers)) {
            ctConstr.setModifiers(Modifier.setPrivate(ctModifiers));
        } else if (Modifier.isProtected(desiredAccessModifiers)) {
            ctConstr.setModifiers(Modifier.setProtected(ctModifiers));
        } else if (!Modifier.isPublic(desiredAccessModifiers)) {
            ctConstr.setModifiers(Modifier.setPackage(ctModifiers));
        } else {
        /* ctConstr remains public */
        }
    }
}
Also used : CtConstructor(javassist.CtConstructor)

Example 52 with CtConstructor

use of javassist.CtConstructor in project drill by apache.

the class GuavaPatcher method patchStopwatch.

/**
   * Makes Guava stopwatch look like the old version for compatibility with hbase-server (for test purposes).
   */
private static void patchStopwatch() throws Exception {
    ClassPool cp = ClassPool.getDefault();
    CtClass cc = cp.get("com.google.common.base.Stopwatch");
    // Expose the constructor for Stopwatch for old libraries who use the pattern new Stopwatch().start().
    for (CtConstructor c : cc.getConstructors()) {
        if (!Modifier.isStatic(c.getModifiers())) {
            c.setModifiers(Modifier.PUBLIC);
        }
    }
    // Add back the Stopwatch.elapsedMillis() method for old consumers.
    CtMethod newmethod = CtNewMethod.make("public long elapsedMillis() { return elapsed(java.util.concurrent.TimeUnit.MILLISECONDS); }", cc);
    cc.addMethod(newmethod);
    // Load the modified class instead of the original.
    cc.toClass();
    logger.info("Google's Stopwatch patched for old HBase Guava version.");
}
Also used : CtClass(javassist.CtClass) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Example 53 with CtConstructor

use of javassist.CtConstructor in project incubator-systemml by apache.

the class GenerateClassesForMLContext method createScriptClass.

/**
 * Convert a script file to a Java class that extends the MLContext API's
 * Script class.
 *
 * @param scriptFilePath
 *            the path to a script file
 */
public static void createScriptClass(String scriptFilePath) {
    try {
        String fullScriptClassName = BASE_DEST_PACKAGE + "." + scriptFilePathToFullClassNameNoBase(scriptFilePath);
        System.out.println("Generating Class: " + fullScriptClassName);
        ClassPool pool = ClassPool.getDefault();
        CtClass ctNewScript = pool.makeClass(fullScriptClassName);
        CtClass ctScript = pool.get(Script.class.getName());
        ctNewScript.setSuperclass(ctScript);
        CtConstructor ctCon = new CtConstructor(null, ctNewScript);
        ctCon.setBody(scriptConstructorBody(scriptFilePath));
        ctNewScript.addConstructor(ctCon);
        addFunctionMethods(scriptFilePath, ctNewScript);
        ctNewScript.writeFile(destination);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CannotCompileException e) {
        e.printStackTrace();
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
}
Also used : CtClass(javassist.CtClass) Script(org.apache.sysml.api.mlcontext.Script) DMLScript(org.apache.sysml.api.DMLScript) ClassPool(javassist.ClassPool) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(javassist.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) CannotCompileException(javassist.CannotCompileException) CtConstructor(javassist.CtConstructor)

Example 54 with CtConstructor

use of javassist.CtConstructor in project incubator-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 55 with CtConstructor

use of javassist.CtConstructor in project core-ng-project by neowu.

the class DynamicInstanceBuilder method constructor.

public void constructor(Class<?>[] constructorParamClasses, String body) {
    if (this.constructorParamClasses != null)
        throw new Error("dynamic class must have no more than one custom constructor");
    sourceCode.constructorParamClasses = constructorParamClasses;
    sourceCode.constructorBody = body;
    try {
        this.constructorParamClasses = constructorParamClasses;
        CtClass[] params = new CtClass[constructorParamClasses.length];
        for (int i = 0; i < constructorParamClasses.length; i++) {
            Class<?> paramClass = constructorParamClasses[i];
            params[i] = classPool.getCtClass(paramClass.getCanonicalName());
        }
        CtConstructor constructor = new CtConstructor(params, classBuilder);
        constructor.setBody(body);
        classBuilder.addConstructor(constructor);
    } catch (CannotCompileException | NotFoundException e) {
        logger.error("constructor body failed to compile:\n{}", body);
        throw new CodeCompileException(e);
    }
}
Also used : CtClass(javassist.CtClass) NotFoundException(javassist.NotFoundException) CannotCompileException(javassist.CannotCompileException) CtConstructor(javassist.CtConstructor)

Aggregations

CtConstructor (javassist.CtConstructor)91 CtClass (javassist.CtClass)66 CtMethod (javassist.CtMethod)38 NotFoundException (javassist.NotFoundException)33 ClassPool (javassist.ClassPool)30 CtField (javassist.CtField)30 CannotCompileException (javassist.CannotCompileException)29 IOException (java.io.IOException)13 Method (java.lang.reflect.Method)9 ArrayList (java.util.ArrayList)7 FileNotFoundException (java.io.FileNotFoundException)6 CtNewMethod (javassist.CtNewMethod)6 MethodInfo (javassist.bytecode.MethodInfo)6 StorageException (org.apache.skywalking.oap.server.core.storage.StorageException)6 StringWriter (java.io.StringWriter)5 ConstPool (javassist.bytecode.ConstPool)5 HashMap (java.util.HashMap)4 Annotation (javassist.bytecode.annotation.Annotation)4 OALCompileException (org.apache.skywalking.oap.server.core.oal.rt.OALCompileException)4 ModuleStartException (org.apache.skywalking.oap.server.library.module.ModuleStartException)4