Search in sources :

Example 6 with CtConstructor

use of javassist.CtConstructor in project yyl_example by Relucent.

the class JavassistGeneratorTest method main.

public static void main(String[] args) throws CannotCompileException, NotFoundException, InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
    //ClassPool是缓存CtClass对象的容器,所有的CtClass对象都在ClassPool中,为了避免内存的消耗,创建ClassPool对象时可以使用单例模式。
    //可以调用CtClass对的detach方法将其从ClassPool中移除。(但是这样的话CtClass就不可用了)
    ClassPool classPool = ClassPool.getDefault();
    //新增一个类定义
    CtClass ctClass = classPool.makeClass("yyl.TestClass");
    //定义类的字段
    CtField ctField = new CtField(classPool.get("java.lang.String"), "name", ctClass);
    //定义字段的修饰符号(这里定义为PRIVATE)
    ctField.setModifiers(Modifier.PRIVATE);
    //添加字段
    ctClass.addField(ctField, Initializer.constant(""));
    //添加私有成员name及其getter、setter方法
    ctClass.addMethod(CtNewMethod.setter("setName", ctField));
    ctClass.addMethod(CtNewMethod.getter("getName", ctField));
    //创建无参的构造体
    CtConstructor cons = new CtConstructor(new CtClass[] {}, ctClass);
    cons.setBody("{name= \"Adam\";}");
    ctClass.addConstructor(cons);
    // 添加有参的构造体
    cons = new CtConstructor(new CtClass[] { classPool.get("java.lang.String") }, ctClass);
    cons.setBody("{$0.name = $1;}");
    ctClass.addConstructor(cons);
    // 调用toClass() 方法时,会将类加载到内存中,类似的方法还有:
    // writeFile() 将class写入到文件中 toBytecode() 输出类的字节码
    // 当CtClass调用writeFile/toClass/toBytecode方法时,Javassist会冻结CtClass(修改将不允许)。
    // 这个主要是为了警告开发者该类已经被加载,而JVM是不允许重新加载该类的。
    // 如果要突破该限制,可以 调用 defrost方法
    // 加载类并打印类名
    System.out.println(ctClass.toClass());
    //#
    // 通过反射获得Class实例
    Class<?> testClass = Class.forName("yyl.TestClass");
    //创建无参的实例,并调用getName方法
    Object o = testClass.newInstance();
    Method getter = testClass.getMethod("getName");
    System.out.println(getter.invoke(o));
    // 调用其setName方法
    Method setter = testClass.getMethod("setName", new Class[] { String.class });
    setter.invoke(o, "Dante");
    System.out.println(getter.invoke(o));
    // 通过反射创建有参的实例,并调用getName方法
    o = Class.forName("yyl.TestClass").getConstructor(String.class).newInstance("Raphael");
    getter = testClass.getMethod("getName");
    System.out.println(getter.invoke(o));
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CtNewMethod(javassist.CtNewMethod) Method(java.lang.reflect.Method) CtConstructor(javassist.CtConstructor)

Example 7 with CtConstructor

use of javassist.CtConstructor in project yyl_example by Relucent.

the class CreateSimpleBeanTest method create.

@SuppressWarnings("unchecked")
public static Class<? extends SimpleBean> create(String className, String... fields) throws CannotCompileException, NotFoundException {
    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.makeClass(className);
    cc.setInterfaces(new CtClass[] { pool.get(SimpleBean.class.getName()) });
    CtClass stringctClass = pool.get("java.lang.String");
    {
        for (String field : fields) {
            cc.addField(new CtField(stringctClass, field, cc));
        }
    }
    {
        CtMethod setCtMethod = new CtMethod(CtClass.voidType, "set", new CtClass[] { stringctClass, stringctClass }, cc);
        setCtMethod.setModifiers(Modifier.PUBLIC);
        StringBuilder vSetBody = new StringBuilder();
        vSetBody.append("if(null == $1){ throw new NullPointerException(\" key can not be NULL \"); }");
        for (String field : fields) {
            vSetBody.append("else if(\"").append(field).append("\".equals($1)){ $0.").append(field).append("=$2; }");
        }
        vSetBody.append("else { throw new IllegalArgumentException(\"Object does not exist in the \" + $1 + \" field\"); }");
        setCtMethod.setBody(vSetBody.toString());
        cc.addMethod(setCtMethod);
    }
    {
        CtMethod getCtMethod = new CtMethod(stringctClass, "get", new CtClass[] { stringctClass }, cc);
        getCtMethod.setModifiers(Modifier.PUBLIC);
        StringBuilder vGetBody = new StringBuilder();
        vGetBody.append("if(null == $1){ throw new NullPointerException(\" key can not be NULL \"); }");
        for (String field : fields) {
            vGetBody.append("else if(\"").append(field).append("\".equals($1)){ return $0.").append(field).append("; }");
        }
        vGetBody.append("else { throw new IllegalArgumentException(\"Object does not exist in the \" + $1 + \" field\"); }");
        getCtMethod.setBody(vGetBody.toString());
        cc.addMethod(getCtMethod);
    }
    {
        CtConstructor cons = new CtConstructor(new CtClass[] {}, cc);
        cons.setBody("{}");
        cc.addConstructor(cons);
    }
    cc.detach();
    return cc.toClass();
}
Also used : CtClass(javassist.CtClass) CtField(javassist.CtField) ClassPool(javassist.ClassPool) CtMethod(javassist.CtMethod) CtConstructor(javassist.CtConstructor)

Example 8 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 9 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 10 with CtConstructor

use of javassist.CtConstructor in project gwt-test-utils by gwt-test-utils.

the class ValueBoxBasePatcher method initClass.

@InitMethod
static void initClass(CtClass c) throws CannotCompileException {
    CtConstructor cons = JavassistUtils.findConstructor(c, Element.class, Renderer.class, Parser.class);
    cons.insertAfter("setText(\"\");");
}
Also used : CtConstructor(javassist.CtConstructor) InitMethod(com.googlecode.gwt.test.patchers.InitMethod)

Aggregations

CtConstructor (javassist.CtConstructor)15 CtClass (javassist.CtClass)8 ClassPool (javassist.ClassPool)6 CtMethod (javassist.CtMethod)5 IOException (java.io.IOException)4 CannotCompileException (javassist.CannotCompileException)4 CtField (javassist.CtField)4 NotFoundException (javassist.NotFoundException)3 InitMethod (com.googlecode.gwt.test.patchers.InitMethod)2 AfterBurnerImpossibleException (com.github.stephanenicolas.afterburner.exception.AfterBurnerImpossibleException)1 GwtTestGWTBridge (com.googlecode.gwt.test.internal.handlers.GwtTestGWTBridge)1 FileNotFoundException (java.io.FileNotFoundException)1 IllegalClassFormatException (java.lang.instrument.IllegalClassFormatException)1 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 ZipException (java.util.zip.ZipException)1 CtNewMethod (javassist.CtNewMethod)1 DMLScript (org.apache.sysml.api.DMLScript)1 Script (org.apache.sysml.api.mlcontext.Script)1 DataIdentifier (org.apache.sysml.parser.DataIdentifier)1