if (bodyTable.containsKey(METHOD_COUNTER) == false) throw new CannotCompileException("no method body: " + METHOD_COUNTER); ClassPool cp = ClassPool.getDefault(); String jar = FileUtil.getJarFileName(PluginLoader.class); if (jar != null) { cp.appendClassPath(jar); CtClass cc = cp.get(superName); CtClass impl = null; CtMethod method_counter = null; try { impl = cp.get(className); impl.defrost(); method_counter = impl.getMethod(METHOD_COUNTER, METHOD_SIGNATURE); } catch (NotFoundException e) { impl = cp.makeClass(className, cc); StringBuffer sb = new StringBuffer(); sb.append("public void ").append(METHOD_COUNTER).append("(").append(METHOD_P1).append(" p1){}"); method_counter = CtNewMethod.make(sb.toString(), impl); impl.addMethod(method_counter); body.append(bodyTable.get(METHOD_COUNTER)); body.append("\n}"); method_counter.setBody(body.toString()); Class c = impl.toClass(new URLClassLoader(new URL[0], this.getClass().getClassLoader()), null); AbstractCounter plugin = (AbstractCounter) c.newInstance();
public Class<?> toClass(ClassLoader loader, ProtectionDomain pd) { if (mCtc != null) { mCtc.detach(); CtClass ctcs = mSuperClass == null ? null : mPool.get(mSuperClass); if (mClassName == null) { mClassName = (mSuperClass == null || javassist.Modifier.isPublic(ctcs.getModifiers()) ? ClassGenerator.class.getName() : mSuperClass + "$sc") + id; mCtc = mPool.makeClass(mClassName); if (mSuperClass != null) { mCtc.setSuperclass(ctcs); mCtc.addInterface(mPool.get(DC.class.getName())); // add dynamic class tag. if (mInterfaces != null) { for (String cl : mInterfaces) { mCtc.addField(CtField.make(code, mCtc)); for (String code : mMethods) { if (code.charAt(0) == ':') { mCtc.addMethod(CtNewMethod.copy(getCtMethod(mCopyMethods.get(code.substring(1))), code.substring(1, code.indexOf('(')), mCtc, null)); } else { mCtc.addMethod(CtNewMethod.make(code, mCtc)); mCtc.addConstructor(CtNewConstructor.defaultConstructor(mCtc));
private CtClass produceProxyClass(CtClass orgclass, Class orgRtClass) throws CannotCompileException, NotFoundException int modify = orgclass.getModifiers(); if (Modifier.isAbstract(modify) || Modifier.isNative(modify) || !Modifier.isPublic(modify)) throw new CannotCompileException(orgclass.getName() + " must be public, non-native, and non-abstract."); CtClass proxy = classPool.makeClass(orgclass.getName(), orgclass.getSuperclass()); = new CtField(classPool.get("javassist.tools.rmi.ObjectImporter"), fieldImporter, proxy); f.setModifiers(Modifier.PRIVATE); proxy.addField(f, CtField.Initializer.byParameter(0)); f = new CtField(CtClass.intType, fieldObjectId, proxy); f.setModifiers(Modifier.PRIVATE); proxy.addField(f, CtField.Initializer.byParameter(1)); proxy.addMethod(CtNewMethod.getter(accessorObjectId, f)); proxy.addConstructor(CtNewConstructor.defaultConstructor(proxy)); CtConstructor cons = CtNewConstructor.skeleton(proxyConstructorParamTypes, null, proxy); proxy.addConstructor(cons);
throws CannotCompileException, NotFoundException if (clazz.getAttribute("Reflective") != null) return false; // this is already reflective. else clazz.setAttribute("Reflective", new byte[0]); CtClass mlevel = classPool.get("javassist.tools.reflect.Metalevel"); boolean addMeta = !clazz.subtypeOf(mlevel); if (addMeta) clazz.addInterface(mlevel); f = new CtField(classPool.get("javassist.tools.reflect.Metaobject"), metaobjectField, clazz); f.setModifiers(Modifier.PROTECTED); clazz.addField(f, CtField.Initializer.byNewWithParams(metaobject)); clazz.addMethod(CtNewMethod.getter(metaobjectGetter, f)); clazz.addMethod(CtNewMethod.setter(metaobjectSetter, f)); f = new CtField(classPool.get("javassist.tools.reflect.ClassMetaobject"), classobjectField, clazz); f.setModifiers(Modifier.PRIVATE | Modifier.STATIC); new String[] { clazz.getName() })); clazz.addMethod(CtNewMethod.getter(classobjectAccessor, f)); return true;
String name = m.getName(); if (m.getDeclaringClass() == clazz) { if (Modifier.isNative(mod)) return; if (Modifier.isFinal(mod)) { mod &= ~Modifier.FINAL; m2.setModifiers(mod); if (Modifier.isFinal(mod)) return; m2 = CtNewMethod.delegator(findOriginal(m, dontSearch), clazz); m2.setModifiers(mod); clazz.addMethod(m2); = CtNewMethod.wrapped(m.getReturnType(), name, m.getParameterTypes(), m.getExceptionTypes(), body, ConstParameter.integer(identifier), clazz); wmethod.setModifiers(mod); clazz.addMethod(wmethod);
int i = name.lastIndexOf('.'); String className = i < 0 ? name : name.substring(i + 1); ClassPool pool = new ClassPool(true); pool.appendClassPath(new LoaderClassPath(ClassHelper.getCallerClassLoader(getClass()))); Matcher matcher = IMPORT_PATTERN.matcher(source); List<String> importPackages = new ArrayList<String>(); if (pkg.endsWith(".*")) { String pkgName = pkg.substring(0, pkg.length() - 2); pool.importPackage(pkgName); importPackages.add(pkgName); } else { ifaceClass = ClassUtils.forName(packages, iface).getName(); cls.addInterface(pool.get(ifaceClass)); if (method.length() > 0) { if (method.startsWith(className)) { cls.addConstructor(CtNewConstructor.make("public " + method, cls)); } else if (FIELD_PATTERN.matcher(method).matches()) { cls.addField(CtField.make("private " + method, cls)); } else { cls.addMethod(CtNewMethod.make("public " + method, cls));
final CtClass cc = pool.makeClass(referenceFullName); final CtClass ccInterface = pool.get(aInterface.getName()); final CtClass ccActorReference = pool.get(RemoteReference.class.getName()); cc.setSuperclass(ccActorReference); cc.addInterface(ccInterface); cc.addConstructor(CtNewConstructor.make(new CtClass[]{ pool.get(String.class.getName()) }, null, "{ super($1); }", cc)); for (final CtMethod m : ccInterface.getMethods()) if (!m.getDeclaringClass().isInterface() || !m.getReturnType().getName().equals(Task.class.getName())) final boolean oneWay = m.hasAnnotation(OneWay.class); final String methodName = m.getName(); cc.addField(CtField.make("private static java.lang.reflect.Method " + methodReferenceField + " = null;", cc)); final CtMethod newMethod = CtNewMethod.make(m.getReturnType(), methodName, parameterTypes, m.getExceptionTypes(), "{ return super.invoke(" + lazyMethodReferenceInit + ", " + oneWay + ", " + methodId + ", $args); }", cc.addMethod(newMethod); cc.addMethod(CtNewMethod.make("protected int _interfaceId() { return " + interfaceId + ";}", cc)); cc.addMethod(CtNewMethod.make("protected Class _interfaceClass() { return " + interfaceFullName + ".class;}", cc)); return loadClass(cc, aInterface);
final CtClass cc = pool.makeClass(invokerFullName); final String className = actorClass.getName(); final CtClass ccInterface = pool.get(className); final CtClass ccActorInvoker = pool.get(ObjectInvoker.class.getName()); cc.setSuperclass(ccActorInvoker); final CtMethod[] declaredMethods = ccInterface.getMethods(); invokerBody.append(" switch(methodId) { "); if (!m.getReturnType().getName().equals(Task.class.getName()) || !Modifier.isPublic(m.getModifiers()) || Modifier.isStatic(m.getModifiers())) + ((parameterTypes.length > 0) ? "[]{" + parameterTypesStr + "}" : "[0]") + ");"; cc.addField(CtField.make(src, cc)); getMethodBody.append("case " + methodId + ": return " + methodField + ";"); cc.addMethod(CtNewMethod.make(invokerBody.toString(), cc)); cc.addMethod(CtNewMethod.make(getMethodBody.toString(), cc)); cc.addMethod(CtNewMethod.make("public Class getInterface() { return " + className + ".class; }", cc));
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(); }
CtClass superCt = classPool.getCtClass(superClassName); CtClass targetCt = classPool.makeClass(newClassName, superCt); targetCt.setModifiers(Modifier.FINAL); targetCt.setModifiers(Modifier.PUBLIC); for (CtMethod method : superCt.getMethods()) { if ((method.getModifiers() & Modifier.FINAL) == Modifier.FINAL) { superSigs.add(method.getName() + method.getSignature()); CtClass intfCt = classPool.getCtClass(intf.getName()); targetCt.addInterface(intfCt); for (CtMethod intfMethod : intfCt.getDeclaredMethods()) { CtMethod method = CtNewMethod.copy(intfMethod, targetCt, null);
private void doInstrument(CtClass target) throws NotFoundException, CannotCompileException { CtMethod[] modelMethods = modelClass.getDeclaredMethods(); CtMethod[] targetMethods = target.getDeclaredMethods(); CtMethod modelGetClass = modelClass.getDeclaredMethod("modelClass"); CtMethod newGetClass = CtNewMethod.copy(modelGetClass, target, null); newGetClass.setBody("{ return " + target.getName() + ".class; }"); int modifiers = method.getModifiers(); if (Modifier.isStatic(modifiers)) { if (targetHasMethod(targetMethods, method)) { Logger.debug("Detected method: " + method.getName() + ", skipping delegate."); } else { CtMethod newMethod; if (Modifier.isProtected(modifiers) || Modifier.isPublic(modifiers)) { newMethod = CtNewMethod.copy(method, target, classMap); newMethod.instrument(conv); } else if ("modelClass".equals(method.getName())) { newMethod = newGetClass; } else { newMethod = CtNewMethod.delegator(method, target);
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; }
ClassPool cp = ClassPool.getDefault(); cp.insertClassPath(new ClassClassPath(ConfigVariationsTestSuiteBuilder.class)); CtClass cl = cp.makeClass(pkg + "." + clsName); cl.setSuperclass(cp.get(cls.getName())); CtMethod mtd = CtNewMethod.make("public static void init() { " + "injectTestsConfiguration(" + ConfigVariationsTestSuiteBuilder.class.getName() ClassFile ccFile = cl.getClassFile(); ConstPool constpool = ccFile.getConstPool(); mtd.getMethodInfo().addAttribute(attr); cl.addMethod(mtd); return cl.toClass();
@Override public Class<?> compile(ClassData classData) throws Exception { String packageName = classData.getPackageName(); String className = classData.getClassName(); String methodText = ((JavaAssistClassData)classData).getMethodText(); String bridgeMethodText = ((JavaAssistClassData)classData).getBridgeMethodText(); ClassPool classPool = new ClassPool(true); CtClass superClass = resolveClass(DefaultFEELLib.class); CtClass superInterface = resolveClass(LambdaExpression.class); CtClass lambdaImplClass = classPool.makeClass(packageName + "." + className); lambdaImplClass.setSuperclass(superClass); lambdaImplClass.addInterface(superInterface); CtMethod applyMethod = CtNewMethod.make(methodText, lambdaImplClass); applyMethod.setModifiers(applyMethod.getModifiers() | Modifier.VARARGS); lambdaImplClass.addMethod(applyMethod); CtMethod applyBridgeMethod = CtMethod.make(bridgeMethodText, lambdaImplClass); lambdaImplClass.addMethod(applyBridgeMethod); return lambdaImplClass.toClass(); }
/** * Create a way to export the hash table where the service container stores * named sbb usage parameters. * * @param sbbConcrete */ private void createNamedUsageParameterSetter(CtClass sbbConcrete) { try { CtField ctField = new CtField(pool.get(Map.class.getName()), "usageParameterTable", sbbConcrete); ctField.setModifiers(Modifier.PRIVATE); sbbConcrete.addField(ctField); CtMethod setNamedUsageParameterTable = CtNewMethod.make( "public void " + NAMED_USAGE_PARAMETER_SETTER + " ( " + Map.class.getName() + " usageParamTable ) {" + "this.usageParameterTable = usageParamTable; }", sbbConcrete); sbbConcrete.addMethod(setNamedUsageParameterTable); } catch (Exception ex) { String s = "Unexpected exception in setNamedUsageParameterTable generation"; logger.fatal(s, ex); } }
ClassPool pool = getClassPool(context, loader); CtClass newClass = pool.makeClass(expression.getClass().getName() + expression.hashCode() + _classCounter++ + "Accessor"); newClass.addInterface(getCtClass(ExpressionAccessor.class)); CtMethod valueGetter = new CtMethod(objClass, "get", new CtClass[]{ognlClass, objClass}, newClass); CtMethod valueSetter = new CtMethod(CtClass.voidType, "set", new CtClass[]{ognlClass, objClass, objClass}, newClass); nodeMember = new CtField(nodeClass, "_node", newClass); newClass.addField(nodeMember); setExpression = CtNewMethod.setter("setExpression", nodeMember); newClass.addMethod(setExpression); nodeMember = new CtField(nodeClass, "_node", newClass); newClass.addField(nodeMember); setExpression = CtNewMethod.setter("setExpression", nodeMember); newClass.addMethod(setExpression); newClass.addConstructor(CtNewConstructor.defaultConstructor(newClass)); Class clazz = pool.toClass(newClass); newClass.detach();
private Class<?> getReturnClass(String className, Map<String, Class<?>> fields) throws CannotCompileException, NotFoundException { String fqClassName = this.getClass().getPackage().getName() + "." + className; try { // see if the class already exists return Class.forName(fqClassName); } catch (ClassNotFoundException e) { // otherwise create the class ClassPool pool = ClassPool.getDefault(); CtClass ctClass = pool.makeClass(fqClassName); for (Map.Entry<String, Class<?>> entry : fields.entrySet()) { // generate a public field (we don't need a setter) String fieldName = entry.getKey(); CtClass valueClass = pool.get(entry.getValue().getName()); CtField ctField = new CtField(valueClass, fieldName, ctClass); ctField.setModifiers(Modifier.PUBLIC); ctClass.addField(ctField); // generate the getter method String methodName = "get" + StringUtils.capitalize(fieldName); CtMethod ctMethod = CtNewMethod.make(valueClass, methodName, new CtClass[] {}, new CtClass[] {}, "{ return this." + fieldName + ";}", ctClass); ctClass.addMethod(ctMethod); } return ctClass.toClass(); } }
.isStatic(originalMethod.getModifiers()) ? ConstantKind.INSTANCE : ConstantKind.CLASS; if (originalMethod.getParameterTypes().length > 0) { context.logInfoMessage("{}: has one or more parameters. Not processing", context.getMethod().getLongName()); return; CtClass clazz = originalMethod.getDeclaringClass(); String methodName = originalMethod.getName(); String fieldType = originalMethod.getReturnType().getName(); String fieldName = constantKind.getFieldName(methodName); CtField field = CtField.make(String.format(constantKind.getFieldTemplate(), fieldType, fieldName), clazz); CtMethod initializer = CtNewMethod.copy( originalMethod, String.format(INITIALIZER_NAME_TEMPLATE, methodName), null); initializer.setModifiers(constantKind.getInitializerModifiers()); clazz.addMethod(initializer); clazz.addField(field, Initializer.byExpr(initializer.getName() + "()")); originalMethod.setBody(String.format(METHOD_TEMPLATE, fieldName));
public <T> Class<T> createClassReplica(Class<T> clazz) { if (clazz == null) { throw new IllegalArgumentException("clazz cannot be null"); } ClassPool classpool = ClassPool.getDefault(); final String originalClassName = clazz.getName(); CtClass originalClassAsCtClass; final CtClass newClass = classpool.makeClass(generateReplicaClassName(clazz)); try { originalClassAsCtClass = classpool.get(originalClassName); CtMethod[] declaredMethods = originalClassAsCtClass.getDeclaredMethods(); for (CtMethod ctMethod : declaredMethods) { final String code = getReplicaMethodDelegationCode(clazz, ctMethod, null); CtNewMethod.make(ctMethod.getReturnType(), ctMethod.getName(), ctMethod.getParameterTypes(), ctMethod.getExceptionTypes(), code, newClass); } return (Class<T>) newClass.toClass(this.getClass().getClassLoader(), this.getClass().getProtectionDomain()); } catch (Exception e) { throw new RuntimeException(e); } }
try ClassPool pool = new ClassPool(true); pool.appendClassPath(new LoaderClassPath(loader)); CtClass clazz = pool.makeClass(wrapperName); clazz.setSuperclass(pool.get(WrapperType.class.getName())); CtField field = new CtField(pool.get(param.getType()), param.getVariable(), clazz); field.setModifiers(Modifier.PRIVATE); clazz.addField(field); clazz.addMethod(CtNewMethod.getter("get" + JavaUtils.capitalize(param.getVariable()), field)); clazz.addMethod(CtNewMethod.setter("set" + JavaUtils.capitalize(param.getVariable()), field));