/** * Compiles the given source code and creates a method. * This method simply delegates to <code>make()</code> in * <code>CtNewMethod</code>. See it for more details. * <code>CtNewMethod</code> has a number of useful factory methods. * * @param src the source text. * @param declaring the class to which the created method is added. * @see CtNewMethod#make(String, CtClass) */ public static CtMethod make(String src, CtClass declaring) throws CannotCompileException { return CtNewMethod.make(src, declaring); }
/** * Compiles the given source code and creates a method. * The source code must include not only the method body * but the whole declaration, for example, * * <pre>"public Object id(Object obj) { return obj; }"</pre> * * @param src the source text. * @param declaring the class to which the created method is added. */ public static CtMethod make(String src, CtClass declaring) throws CannotCompileException { return make(src, declaring, null, null); }
/** * Creates a public (non-static) method. The created method cannot * be changed to a static method later. * * @param returnType the type of the returned value. * @param mname the method name. * @param parameters a list of the parameter types. * @param exceptions a list of the exception types. * @param body the source text of the method body. * It must be a block surrounded by <code>{}</code>. * If it is <code>null</code>, the created method * does nothing except returning zero or null. * @param declaring the class to which the created method is added. * @see #make(int, CtClass, String, CtClass[], CtClass[], String, CtClass) */ public static CtMethod make(CtClass returnType, String mname, CtClass[] parameters, CtClass[] exceptions, String body, CtClass declaring) throws CannotCompileException { return make(Modifier.PUBLIC, returnType, mname, parameters, exceptions, body, declaring); }
/** * Compiles the given source code and creates a method. * This method simply delegates to <code>make()</code> in * <code>CtNewMethod</code>. See it for more details. * <code>CtNewMethod</code> has a number of useful factory methods. * * @param src the source text. * @param declaring the class to which the created method is added. * @see CtNewMethod#make(String, CtClass) */ public static CtMethod make(String src, CtClass declaring) throws CannotCompileException { return CtNewMethod.make(src, declaring); }
/** * Compiles the given source code and creates a method. * The source code must include not only the method body * but the whole declaration, for example, * * <pre>"public Object id(Object obj) { return obj; }"</pre> * * @param src the source text. * @param declaring the class to which the created method is added. */ public static CtMethod make(String src, CtClass declaring) throws CannotCompileException { return make(src, declaring, null, null); }
public Proxy<I> addMethod(String code) { return handleException(() -> ctClass.addMethod(CtNewMethod.make(code, ctClass))); }
/** * convenience method that builds a method from a format string. {@see String.format} for more details * * @throws CannotCompileException */ public static CtMethod write(CtClass target, String format, Object ... args) throws CannotCompileException { String body = String.format( format, args ); // System.out.printf( "writing method into [%s]:%n%s%n", target.getName(), body ); log.debugf( "writing method into [%s]:%n%s", target.getName(), body ); CtMethod method = CtNewMethod.make( body, target ); target.addMethod( method ); return method; }
public static Decoder gen(String cacheKey, String source) throws Exception { Decoder decoder; CtClass ctClass = pool.makeClass(cacheKey); ctClass.setInterfaces(new CtClass[]{pool.get(Decoder.class.getName())}); CtMethod staticMethod = CtNewMethod.make(source, ctClass); ctClass.addMethod(staticMethod); CtMethod interfaceMethod = CtNewMethod.make("" + "public Object decode(com.jsoniter.JsonIterator iter) {" + "return decode_(iter);" + "}", ctClass); ctClass.addMethod(interfaceMethod); decoder = (Decoder) ctClass.toClass().newInstance(); return decoder; }
cls.addField(CtField.make("private " + method, cls)); } else { cls.addMethod(CtNewMethod.make("public " + method, cls));
cls.addField(CtField.make("private " + method, cls)); } else { cls.addMethod(CtNewMethod.make("public " + method, cls));
private static TemplateRenderer tryToCompile(String source, Map<String, String> expressions, Map<String, String> constants, Class<?> modelType) throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException { ClassPool cp = ClassPool.getDefault(); CtClass sup = cp.get(Object.class.getCanonicalName()); CtClass cls = cp.makeClass("RapidoidTemplate" + ID_GEN.incrementAndGet(), sup); cls.addInterface(cp.get(TemplateRenderer.class.getCanonicalName())); cls.addConstructor(CtNewConstructor.defaultConstructor(cls)); addExpressions(expressions, cls); addConstants(constants, cls); CtClass[] params = {cp.get(RenderCtx.class.getCanonicalName())}; CtClass clsVoid = cp.get(void.class.getCanonicalName()); cls.addMethod(CtNewMethod.make(Modifier.PUBLIC, clsVoid, "render", params, new CtClass[0], source, cls)); return (TemplateRenderer) cls.toClass().newInstance(); }
public static Encoder gen(Class clazz, String cacheKey, CodegenResult source) throws Exception { source.flushBuffer(); CtClass ctClass = pool.makeClass(cacheKey); ctClass.setInterfaces(new CtClass[]{pool.get(Encoder.class.getName())}); String staticCode = source.toString(); CtMethod staticMethod = CtNewMethod.make(staticCode, ctClass); ctClass.addMethod(staticMethod); String wrapperCode = source.generateWrapperCode(clazz); if ("true".equals(System.getenv("JSONITER_DEBUG"))) { System.out.println(">>> " + cacheKey); System.out.println(wrapperCode); System.out.println(staticCode); } CtMethod interfaceMethod = CtNewMethod.make(wrapperCode, ctClass); ctClass.addMethod(interfaceMethod); return (Encoder) ctClass.toClass().newInstance(); } }
@Override public <T> ObjectConstructor<T> createConstructor(Class<T> type) throws NoSuchMethodException { String constructorClassName = type.getName() + "_ReflectConstructor"; try { return (ObjectConstructor<T>) type.getClassLoader().loadClass(constructorClassName).getConstructor().newInstance(); } catch (ClassNotFoundException ignored) { try { if (Modifier.isPrivate(type.getDeclaredConstructor().getModifiers())) { logger.warn("Constructor for '{}' exists but is private, falling back on reflection", type); return backupFactory.createConstructor(type); } CtClass constructorClass = pool.makeClass(type.getName() + "_ReflectConstructor"); constructorClass.setInterfaces(new CtClass[]{objectConstructorInterface}); CtMethod method = CtNewMethod.make("public Object construct() { return new " + type.getName() + "();}", constructorClass); constructorClass.addMethod(method); return (ObjectConstructor<T>) (constructorClass.toClass(type.getClassLoader(), type.getProtectionDomain()).getConstructor().newInstance()); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | CannotCompileException e) { logger.error("Error instantiating constructor object for '{}', falling back on reflection", type, e); return backupFactory.createConstructor(type); } catch (NoSuchMethodException e) { return null; } } catch (InvocationTargetException | InstantiationException | IllegalAccessException e) { logger.error("Error instantiating constructor object for '{}', falling back on reflection", type, e); return backupFactory.createConstructor(type); } }
private void ensureNewInstance(CtClass cc) throws NotFoundException, CannotCompileException { CtMethod ccms[] = cc.getDeclaredMethods(); if( !javassist.Modifier.isAbstract(cc.getModifiers()) && !hasExisting("newInstance", "()Lwater/Freezable;", ccms) ) { cc.addMethod(CtNewMethod.make( "public water.Freezable newInstance() {\n" + " return new " +cc.getName()+"();\n" + "}", cc)); } }
private CtClass createPatchesInfoClass() { try { CtClass ctPatchesInfoImpl = classPool.makeClass(Config.patchPackageName + ".PatchesInfoImpl"); ctPatchesInfoImpl.getClassFile().setMajorVersion(ClassFile.JAVA_7); ctPatchesInfoImpl.setInterfaces(new CtClass[]{classPool.get("com.meituan.robust.PatchesInfo")}); StringBuilder methodBody = new StringBuilder(); methodBody.append("public java.util.List getPatchedClassesInfo() {"); methodBody.append(" java.util.List patchedClassesInfos = new java.util.ArrayList();"); for (int i = 0; i < Config.modifiedClassNameList.size(); i++) { if (Constants.OBSCURE) { methodBody.append("com.meituan.robust.PatchedClassInfo patchedClass" + i + " = new com.meituan.robust.PatchedClassInfo(\"" + ReadMapping.getInstance().getClassMappingOrDefault(Config.modifiedClassNameList.get(i)).getValueName() + "\",\"" + NameManger.getInstance().getPatchControlName(Config.modifiedClassNameList.get(i).substring(Config.modifiedClassNameList.get(i).lastIndexOf('.') + 1)) + "\");"); } else { methodBody.append("com.meituan.robust.PatchedClassInfo patchedClass" + i + " = new com.meituan.robust.PatchedClassInfo(\"" + Config.modifiedClassNameList.get(i) + "\",\"" + NameManger.getInstance().getPatchControlName(Config.modifiedClassNameList.get(i).substring(Config.modifiedClassNameList.get(i).lastIndexOf('.') + 1)) + "\");"); } methodBody.append("patchedClassesInfos.add(patchedClass" + i + ");"); } methodBody.append(Constants.ROBUST_UTILS_FULL_NAME + ".isThrowable=!" + Config.catchReflectException + ";"); methodBody.append("return patchedClassesInfos;\n" + " }"); CtMethod m = make(methodBody.toString(), ctPatchesInfoImpl); ctPatchesInfoImpl.addMethod(m); return ctPatchesInfoImpl; } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
private void exposeRawEnumArray(CtClass cc) throws NotFoundException, CannotCompileException { CtField field; try { field = cc.getField("$VALUES"); } catch( NotFoundException nfe ) { // Eclipse apparently stores this in a different place. field = cc.getField("ENUM$VALUES"); } String body = "public static "+cc.getName()+" raw_enum(int i) { return i==255?null:"+field.getName()+"[i]; } "; try { cc.addMethod(CtNewMethod.make(body,cc)); } catch( CannotCompileException ce ) { Log.warn(Sys.WATER,"--- Compilation failure while compiler raw_enum for "+cc.getName()+"\n"+body+"\n------",ce); throw ce; } }
code.substring(1, code.indexOf('(')), mCtc, null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc));
code.substring(1, code.indexOf('(')), mCtc, null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc));
private void ensureType(CtClass cc) throws NotFoundException, CannotCompileException { CtMethod ccms[] = cc.getDeclaredMethods(); if( !javassist.Modifier.isAbstract(cc.getModifiers()) && !hasExisting("frozenType", "()I", ccms) ) { // Build a simple field & method returning the type token cc.addField(new CtField(CtClass.intType, "_frozen$type", cc)); cc.addMethod(CtNewMethod.make("public int frozenType() {" + " return _frozen$type == 0 ? (_frozen$type=water.TypeMap.onIce(\""+cc.getName()+"\")) : _frozen$type;" + "}",cc)); } }
private void ensureVersion(CtClass cc) throws NotFoundException, CannotCompileException, BadBytecode { CtMethod ccms[] = cc.getDeclaredMethods(); if (!javassist.Modifier.isAbstract(cc.getModifiers())) { String gsig = cc.getGenericSignature(); ClassSignature csig = SignatureAttribute.toClassSignature(gsig); // Warning: this is not doing proper parent (superclass/interfaces) traversal TypeArgument ta = getTypeArg(csig.getSuperClass().getTypeArguments(), "Lwater/api/rest/Version"); if (ta!=null && !hasExisting("getVersion", "()"+ta.getType().encode(), ccms) ) { String typeName = ta.toString(); String valueName = getValueFromType(typeName); //cc.addMethod(CtNewMethod.make("public "+typeName+" getVersion() {" + cc.addMethod(CtNewMethod.make("public water.api.rest.Version getVersion() {" + " return "+valueName+";" + "}",cc)); } } } private String getValueFromType(String typeName) {