List of usage examples for org.objectweb.asm Opcodes ACC_SUPER
int ACC_SUPER
To view the source code for org.objectweb.asm Opcodes ACC_SUPER.
Click Source Link
From source file:org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator.java
License:Apache License
private static byte[] generateProxyClassBytes(Class<?> targetClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) { Class<?> superClass = targetClass; String[] interfaces = new String[] {}; if (targetClass.isInterface()) { superClass = Object.class; interfaces = new String[] { Type.getInternalName(targetClass) }; }//from w ww .j a va 2s. c o m // add DeltaSpikeProxy as interface interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class); if (additionalInterfaces != null && additionalInterfaces.length > 0) { interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length); for (int i = 0; i < additionalInterfaces.length; i++) { interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]); } } Type superType = Type.getType(superClass); Type proxyType = Type.getObjectType(proxyName); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces); defineDefaultConstructor(cw, proxyType, superType); defineDeltaSpikeProxyFields(cw); defineDeltaSpikeProxyMethods(cw, proxyType); if (delegateMethods != null) { for (java.lang.reflect.Method method : delegateMethods) { defineMethod(cw, method, proxyType); } } if (interceptMethods != null) { for (java.lang.reflect.Method method : interceptMethods) { defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix); defineMethod(cw, method, proxyType); } } // copy all annotations from the source class try { // ClassVisitor to intercept all annotation visits on the class ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new CopyAnnotationVisitorAdapter(super.visitAnnotation(desc, visible), cw.visitAnnotation(desc, visible)); } }; // visit class to proxy with our visitor to copy all annotations from the source class to our ClassWriter String sourceClassFilename = targetClass.getName().replace('.', '/') + ".class"; ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(sourceClassFilename)); cr.accept(cv, 0); } catch (Exception e) { throw new RuntimeException(e); } return cw.toByteArray(); }
From source file:org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator.java
License:Apache License
private static byte[] generateProxyClassBytes(Class<?> targetClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) { Class<?> superClass = targetClass; String[] interfaces = new String[] {}; if (targetClass.isInterface()) { superClass = Object.class; interfaces = new String[] { Type.getInternalName(targetClass) }; }//from w ww . ja va 2 s . c om // add DeltaSpikeProxy as interface interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class); if (additionalInterfaces != null && additionalInterfaces.length > 0) { interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length); for (int i = 0; i < additionalInterfaces.length; i++) { interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]); } } Type superType = Type.getType(superClass); Type proxyType = Type.getObjectType(proxyName); Type delegateInvocationHandlerType = Type.getType(InvocationHandler.class); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces); defineInvocationHandlerField(cw, delegateInvocationHandlerType); defineDefaultConstructor(cw, proxyType, superType); defineDelegateInvocationHandlerConstructor(cw, proxyType, superType, delegateInvocationHandlerType); defineDeltaSpikeProxyMethods(cw, proxyType, delegateInvocationHandlerType); if (delegateMethods != null) { for (java.lang.reflect.Method method : delegateMethods) { defineMethod(cw, method, DelegateManualInvocationHandler.class); } } if (interceptMethods != null) { for (java.lang.reflect.Method method : interceptMethods) { defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix); defineMethod(cw, method, InterceptManualInvocationHandler.class); } } // copy all annotations from the source class try { // ClassVisitor to intercept all annotation visits on the class ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new CopyAnnotationVisitorAdapter(super.visitAnnotation(desc, visible), cw.visitAnnotation(desc, visible)); } }; // visit class to proxy with our visitor to copy all annotations from the source class to our ClassWriter String sourceClassFilename = targetClass.getName().replace('.', '/') + ".class"; ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(sourceClassFilename)); cr.accept(cv, 0); } catch (Exception e) { throw new RuntimeException(e); } return cw.toByteArray(); }
From source file:org.apache.deltaspike.proxy.util.AsmProxyClassGenerator.java
License:Apache License
private static byte[] generateProxyClassBytes(Class<?> targetClass, Class<? extends InvocationHandler> invocationHandlerClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) { Class<?> superClass = targetClass; String[] interfaces = new String[] {}; if (targetClass.isInterface()) { superClass = Object.class; interfaces = new String[] { Type.getInternalName(targetClass) }; }/*from w w w . jav a 2 s.c om*/ // add DeltaSpikeProxy as interface interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class); if (additionalInterfaces != null && additionalInterfaces.length > 0) { interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length); for (int i = 0; i < additionalInterfaces.length; i++) { interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]); } } Type superType = Type.getType(superClass); Type proxyType = Type.getObjectType(proxyName); Type invocationHandlerType = Type.getType(invocationHandlerClass); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces); // copy annotations for (Annotation annotation : targetClass.getDeclaredAnnotations()) { cw.visitAnnotation(Type.getDescriptor(annotation.annotationType()), true).visitEnd(); } defineInvocationHandlerField(cw, invocationHandlerType); defineDefaultConstructor(cw, proxyType, superType); defineDelegateInvocationHandlerConstructor(cw, proxyType, superType, invocationHandlerType); defineDeltaSpikeProxyMethods(cw, proxyType, invocationHandlerType); for (java.lang.reflect.Method method : delegateMethods) { defineMethod(cw, method, DelegateManualInvocationHandler.class); } for (java.lang.reflect.Method method : interceptMethods) { defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix); defineMethod(cw, method, InterceptManualInvocationHandler.class); } return cw.toByteArray(); }
From source file:org.apache.lucene.expressions.js.JavascriptCompiler.java
License:Apache License
/** * Sends the bytecode of class file to {@link ClassWriter}. *///from w w w .ja va 2 s . c om private void generateClass(final ParseTree parseTree, final ClassWriter classWriter, final Map<String, Integer> externalsMap) throws ParseException { classWriter.visit(CLASSFILE_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL, COMPILED_EXPRESSION_INTERNAL, null, EXPRESSION_TYPE.getInternalName(), null); final String clippedSourceText = (sourceText.length() <= MAX_SOURCE_LENGTH) ? sourceText : (sourceText.substring(0, MAX_SOURCE_LENGTH - 3) + "..."); classWriter.visitSource(clippedSourceText, null); final GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC, EXPRESSION_CTOR, null, null, classWriter); constructor.loadThis(); constructor.loadArgs(); constructor.invokeConstructor(EXPRESSION_TYPE, EXPRESSION_CTOR); constructor.returnValue(); constructor.endMethod(); final GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC, EVALUATE_METHOD, null, null, classWriter); // to completely hide the ANTLR visitor we use an anonymous impl: new JavascriptBaseVisitor<Void>() { private final Deque<Type> typeStack = new ArrayDeque<>(); @Override public Void visitCompile(JavascriptParser.CompileContext ctx) { typeStack.push(Type.DOUBLE_TYPE); visit(ctx.expression()); typeStack.pop(); return null; } @Override public Void visitPrecedence(JavascriptParser.PrecedenceContext ctx) { visit(ctx.expression()); return null; } @Override public Void visitNumeric(JavascriptParser.NumericContext ctx) { if (ctx.HEX() != null) { pushLong(Long.parseLong(ctx.HEX().getText().substring(2), 16)); } else if (ctx.OCTAL() != null) { pushLong(Long.parseLong(ctx.OCTAL().getText().substring(1), 8)); } else if (ctx.DECIMAL() != null) { gen.push(Double.parseDouble(ctx.DECIMAL().getText())); gen.cast(Type.DOUBLE_TYPE, typeStack.peek()); } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } return null; } @Override public Void visitExternal(JavascriptParser.ExternalContext ctx) { String text = ctx.VARIABLE().getText(); int arguments = ctx.expression().size(); boolean parens = ctx.LP() != null && ctx.RP() != null; Method method = parens ? functions.get(text) : null; try { if (method != null) { int arity = method.getParameterTypes().length; if (arguments != arity) { throw new ParseException("Invalid expression '" + sourceText + "': Expected (" + arity + ") arguments for function call (" + text + "), but found (" + arguments + ").", ctx.start.getStartIndex()); } typeStack.push(Type.DOUBLE_TYPE); for (int argument = 0; argument < arguments; ++argument) { visit(ctx.expression(argument)); } typeStack.pop(); gen.invokeStatic(Type.getType(method.getDeclaringClass()), org.objectweb.asm.commons.Method.getMethod(method)); gen.cast(Type.DOUBLE_TYPE, typeStack.peek()); } else if (!parens || arguments == 0 && text.contains(".")) { int index; text = normalizeQuotes(ctx.getText()); if (externalsMap.containsKey(text)) { index = externalsMap.get(text); } else { index = externalsMap.size(); externalsMap.put(text, index); } gen.loadArg(0); gen.push(index); gen.arrayLoad(FUNCTION_VALUES_TYPE); gen.invokeVirtual(FUNCTION_VALUES_TYPE, DOUBLE_VAL_METHOD); gen.cast(Type.DOUBLE_TYPE, typeStack.peek()); } else { throw new ParseException("Invalid expression '" + sourceText + "': Unrecognized function call (" + text + ").", ctx.start.getStartIndex()); } return null; } catch (ParseException e) { // The API doesn't allow checked exceptions here, so propagate up the stack. This is unwrapped // in getAntlrParseTree. throw new RuntimeException(e); } } @Override public Void visitUnary(JavascriptParser.UnaryContext ctx) { if (ctx.BOOLNOT() != null) { Label labelNotTrue = new Label(); Label labelNotReturn = new Label(); typeStack.push(Type.INT_TYPE); visit(ctx.expression()); typeStack.pop(); gen.visitJumpInsn(Opcodes.IFEQ, labelNotTrue); pushBoolean(false); gen.goTo(labelNotReturn); gen.visitLabel(labelNotTrue); pushBoolean(true); gen.visitLabel(labelNotReturn); } else if (ctx.BWNOT() != null) { typeStack.push(Type.LONG_TYPE); visit(ctx.expression()); typeStack.pop(); gen.push(-1L); gen.visitInsn(Opcodes.LXOR); gen.cast(Type.LONG_TYPE, typeStack.peek()); } else if (ctx.ADD() != null) { visit(ctx.expression()); } else if (ctx.SUB() != null) { typeStack.push(Type.DOUBLE_TYPE); visit(ctx.expression()); typeStack.pop(); gen.visitInsn(Opcodes.DNEG); gen.cast(Type.DOUBLE_TYPE, typeStack.peek()); } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } return null; } @Override public Void visitMuldiv(JavascriptParser.MuldivContext ctx) { int opcode; if (ctx.MUL() != null) { opcode = Opcodes.DMUL; } else if (ctx.DIV() != null) { opcode = Opcodes.DDIV; } else if (ctx.REM() != null) { opcode = Opcodes.DREM; } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } pushArith(opcode, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitAddsub(JavascriptParser.AddsubContext ctx) { int opcode; if (ctx.ADD() != null) { opcode = Opcodes.DADD; } else if (ctx.SUB() != null) { opcode = Opcodes.DSUB; } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } pushArith(opcode, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBwshift(JavascriptParser.BwshiftContext ctx) { int opcode; if (ctx.LSH() != null) { opcode = Opcodes.LSHL; } else if (ctx.RSH() != null) { opcode = Opcodes.LSHR; } else if (ctx.USH() != null) { opcode = Opcodes.LUSHR; } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } pushShift(opcode, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBoolcomp(JavascriptParser.BoolcompContext ctx) { int opcode; if (ctx.LT() != null) { opcode = GeneratorAdapter.LT; } else if (ctx.LTE() != null) { opcode = GeneratorAdapter.LE; } else if (ctx.GT() != null) { opcode = GeneratorAdapter.GT; } else if (ctx.GTE() != null) { opcode = GeneratorAdapter.GE; } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } pushCond(opcode, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBooleqne(JavascriptParser.BooleqneContext ctx) { int opcode; if (ctx.EQ() != null) { opcode = GeneratorAdapter.EQ; } else if (ctx.NE() != null) { opcode = GeneratorAdapter.NE; } else { throw new IllegalStateException("Unknown operation specified: " + ctx.getText()); } pushCond(opcode, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBwand(JavascriptParser.BwandContext ctx) { pushBitwise(Opcodes.LAND, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBwxor(JavascriptParser.BwxorContext ctx) { pushBitwise(Opcodes.LXOR, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBwor(JavascriptParser.BworContext ctx) { pushBitwise(Opcodes.LOR, ctx.expression(0), ctx.expression(1)); return null; } @Override public Void visitBooland(JavascriptParser.BoolandContext ctx) { Label andFalse = new Label(); Label andEnd = new Label(); typeStack.push(Type.INT_TYPE); visit(ctx.expression(0)); gen.visitJumpInsn(Opcodes.IFEQ, andFalse); visit(ctx.expression(1)); gen.visitJumpInsn(Opcodes.IFEQ, andFalse); typeStack.pop(); pushBoolean(true); gen.goTo(andEnd); gen.visitLabel(andFalse); pushBoolean(false); gen.visitLabel(andEnd); return null; } @Override public Void visitBoolor(JavascriptParser.BoolorContext ctx) { Label orTrue = new Label(); Label orEnd = new Label(); typeStack.push(Type.INT_TYPE); visit(ctx.expression(0)); gen.visitJumpInsn(Opcodes.IFNE, orTrue); visit(ctx.expression(1)); gen.visitJumpInsn(Opcodes.IFNE, orTrue); typeStack.pop(); pushBoolean(false); gen.goTo(orEnd); gen.visitLabel(orTrue); pushBoolean(true); gen.visitLabel(orEnd); return null; } @Override public Void visitConditional(JavascriptParser.ConditionalContext ctx) { Label condFalse = new Label(); Label condEnd = new Label(); typeStack.push(Type.INT_TYPE); visit(ctx.expression(0)); typeStack.pop(); gen.visitJumpInsn(Opcodes.IFEQ, condFalse); visit(ctx.expression(1)); gen.goTo(condEnd); gen.visitLabel(condFalse); visit(ctx.expression(2)); gen.visitLabel(condEnd); return null; } private void pushArith(int operator, ExpressionContext left, ExpressionContext right) { pushBinaryOp(operator, left, right, Type.DOUBLE_TYPE, Type.DOUBLE_TYPE, Type.DOUBLE_TYPE); } private void pushShift(int operator, ExpressionContext left, ExpressionContext right) { pushBinaryOp(operator, left, right, Type.LONG_TYPE, Type.INT_TYPE, Type.LONG_TYPE); } private void pushBitwise(int operator, ExpressionContext left, ExpressionContext right) { pushBinaryOp(operator, left, right, Type.LONG_TYPE, Type.LONG_TYPE, Type.LONG_TYPE); } private void pushBinaryOp(int operator, ExpressionContext left, ExpressionContext right, Type leftType, Type rightType, Type returnType) { typeStack.push(leftType); visit(left); typeStack.pop(); typeStack.push(rightType); visit(right); typeStack.pop(); gen.visitInsn(operator); gen.cast(returnType, typeStack.peek()); } private void pushCond(int operator, ExpressionContext left, ExpressionContext right) { Label labelTrue = new Label(); Label labelReturn = new Label(); typeStack.push(Type.DOUBLE_TYPE); visit(left); visit(right); typeStack.pop(); gen.ifCmp(Type.DOUBLE_TYPE, operator, labelTrue); pushBoolean(false); gen.goTo(labelReturn); gen.visitLabel(labelTrue); pushBoolean(true); gen.visitLabel(labelReturn); } private void pushBoolean(boolean truth) { switch (typeStack.peek().getSort()) { case Type.INT: gen.push(truth); break; case Type.LONG: gen.push(truth ? 1L : 0L); break; case Type.DOUBLE: gen.push(truth ? 1. : 0.); break; default: throw new IllegalStateException("Invalid expected type: " + typeStack.peek()); } } private void pushLong(long i) { switch (typeStack.peek().getSort()) { case Type.INT: gen.push((int) i); break; case Type.LONG: gen.push(i); break; case Type.DOUBLE: gen.push((double) i); break; default: throw new IllegalStateException("Invalid expected type: " + typeStack.peek()); } } }.visit(parseTree); gen.returnValue(); gen.endMethod(); classWriter.visitEnd(); }
From source file:org.apache.lucene.expressions.js.XJavascriptCompiler.java
License:Apache License
private void beginCompile() { classWriter.visit(CLASSFILE_VERSION, Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL | Opcodes.ACC_SYNTHETIC, COMPILED_EXPRESSION_INTERNAL, null, EXPRESSION_TYPE.getInternalName(), null); String clippedSourceText = (sourceText.length() <= MAX_SOURCE_LENGTH) ? sourceText : (sourceText.substring(0, MAX_SOURCE_LENGTH - 3) + "..."); classWriter.visitSource(clippedSourceText, null); GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, EXPRESSION_CTOR, null, null, classWriter); constructor.loadThis();/*from www.j a v a2s .com*/ constructor.loadArgs(); constructor.invokeConstructor(EXPRESSION_TYPE, EXPRESSION_CTOR); constructor.returnValue(); constructor.endMethod(); gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC | Opcodes.ACC_SYNTHETIC, EVALUATE_METHOD, null, null, classWriter); }
From source file:org.batoo.jpa.core.impl.instance.Enhancer.java
License:Open Source License
/** * Returns the enhanced class bytecode./* w w w . j av a 2 s . co m*/ * * @param clazz * the class to enhance * @return the enhanced class * @throws Exception * thrown in case of an error * * @since 2.0.0 */ //@formatter:off public static byte[] create(Class<?> clazz) throws Exception { final String enhancingClassName = Type.getInternalName(clazz); final String enhancedClassName = enhancingClassName + Enhancer.SUFFIX_ENHANCED; final String descEnhancer = Enhancer.makeClassDesc(enhancedClassName); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, enhancedClassName, null, enhancingClassName, new String[] { Type.getInternalName(EnhancedInstance.class) }); // Field: serialVersionUID cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_STATIC, Enhancer.FIELD_SERIAL_VERSION_UID, Type.getDescriptor(Long.TYPE), null, Long.valueOf(1L)) .visitEnd(); // Container fields cw.visitField(Opcodes.ACC_PRIVATE, Enhancer.FIELD_ENHANCED_INITIALIZED, Enhancer.DESCRIPTOR_BOOLEAN, null, null).visitEnd(); cw.visitField(Opcodes.ACC_PRIVATE, Enhancer.FIELD_ENHANCED_INTERNAL, Enhancer.DESCRIPTOR_BOOLEAN, null, null).visitEnd(); cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_TRANSIENT, Enhancer.FIELD_ENHANCED_ID, Enhancer.DESCRIPTOR_OBJECT, null, null).visitEnd(); cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_TRANSIENT, Enhancer.FIELD_ENHANCED_TYPE, Enhancer.DESCRIPTOR_CLASS, null, null).visitEnd(); cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_FINAL + Opcodes.ACC_TRANSIENT, Enhancer.FIELD_ENHANCED_SESSION, Enhancer.DESCRIPTOR_SESSION, null, null).visitEnd(); cw.visitField(Opcodes.ACC_PRIVATE + Opcodes.ACC_TRANSIENT, Enhancer.FIELD_ENHANCED_MANAGED_INSTANCE, Enhancer.DESCRIPTOR_MANAGED_INSTANCE, null, null).visitEnd(); // Constructors Enhancer.createNoArgConstructor(enhancingClassName, enhancedClassName, descEnhancer, cw); Enhancer.createContainerConstructor(enhancingClassName, enhancedClassName, descEnhancer, cw); Enhancer.createMethodIsInitialized(enhancedClassName, descEnhancer, cw); Enhancer.createMethodSetInitialized(enhancedClassName, descEnhancer, cw); Enhancer.createMethodCheck(enhancedClassName, descEnhancer, cw); Enhancer.createMethodGetManagedInstance(enhancedClassName, descEnhancer, cw); Enhancer.createMethodSetManagedInstance(enhancedClassName, descEnhancer, cw); Enhancer.createMethodSetInternal(enhancedClassName, descEnhancer, cw); final Map<String, Method> methods = Maps.newHashMap(); Class<?> currentClass = clazz; while (currentClass != Object.class) { // we are not interested in Object.class for (final Method method : currentClass.getDeclaredMethods()) { int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers) || Modifier.isStatic(modifiers) || Modifier.isPrivate(modifiers) || method.isSynthetic() || method.isBridge()) { continue; } // Filter out the details that we are not interested modifiers &= Modifier.ABSTRACT; modifiers &= Modifier.FINAL; modifiers &= Modifier.NATIVE; modifiers &= Modifier.PRIVATE; modifiers &= Modifier.PROTECTED; modifiers &= Modifier.STATIC; modifiers &= Modifier.STRICT; if ((modifiers == Modifier.PUBLIC) || (modifiers == 0)) { // we are not interested in the return type to omit the overridden methods final String desc = method.getName() + Enhancer.makeDescription(Void.TYPE, method.getParameterTypes()); if (methods.get(desc) == null) { methods.put(desc, method); } } } currentClass = currentClass.getSuperclass(); } for (final Method method : methods.values()) { if (!Enhancer.IGNORED_METHODS.contains(method.getName())) { Enhancer.createOverrriddenMethod(enhancingClassName, enhancedClassName, descEnhancer, cw, method); } } cw.visitEnd(); return cw.toByteArray(); }
From source file:org.compass.core.util.reflection.asm.AsmReflectionConstructorGenerator.java
License:Apache License
/** * Allows to generate an {@link ReflectionConstructor} implementation based on ASM that does not use * reflection./* w ww. j a v a2s. com*/ */ public static synchronized ReflectionConstructor generateConstructor(Constructor originalCtor) throws NoSuchMethodException { final Class declaringClass = originalCtor.getDeclaringClass(); String ownerClassName = declaringClass.getName(); Constructor[] declaredCtors = declaringClass.getDeclaredConstructors(); int ctorIndex = 0; for (; ctorIndex < declaredCtors.length; ++ctorIndex) { if (declaredCtors[ctorIndex].equals(originalCtor)) break; } String className = ownerClassName + "ConstReflection" + ctorIndex; try { Class definedClass; try {// checks if was already loaded definedClass = declaringClass.getClassLoader().loadClass(className); } catch (ClassNotFoundException e) // need to build a new class { String classInternalName = className.replace('.', '/'); // build internal name for ASM ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, classInternalName, null, OBJECT_INTERNAL_NAME, REFLECTIONCONSTRUCTOR_INTERNAL_NAME); createConstructor(cw); createNewInstanceMethod(cw, declaringClass); cw.visitEnd(); byte[] b = cw.toByteArray(); definedClass = defineClass(declaringClass.getClassLoader(), className, b); } return (ReflectionConstructor) definedClass.newInstance(); } catch (Exception e) { NoSuchMethodException ex = new NoSuchMethodException( "Can't create ASM constructor reflection helper for [" + originalCtor + "]"); ex.initCause(e); throw ex; } }
From source file:org.compass.core.util.reflection.asm.AsmReflectionFieldGenerator.java
License:Apache License
/** * Allows to generate {@link org.compass.core.util.reflection.ReflectionField} implementation based on * ASM that does not use reflection.//from w ww . j a va 2s . c om */ public static synchronized ReflectionField generateField(Field refField) throws NoSuchFieldException { Class declaringClass = refField.getDeclaringClass(); String ownerClassName = declaringClass.getName(); Field[] declaredFields = declaringClass.getDeclaredFields(); int methodIndex = 0; for (; methodIndex < declaredFields.length; ++methodIndex) { if (declaredFields[methodIndex].equals(refField)) break; } String className = ownerClassName + "FieldReflection" + methodIndex; try { Class definedClass; try { // checks if was already loaded definedClass = declaringClass.getClassLoader().loadClass(className); } catch (ClassNotFoundException e) // need to build a new class { String classInternalName = className.replace('.', '/'); // build internal name for ASM ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, classInternalName, null, PLAIN_FIELD_INTERNAL_NAME, null); createConstructor(cw); createGetMethod(cw, declaringClass, refField); createSetMethod(cw, declaringClass, refField); cw.visitEnd(); byte[] b = cw.toByteArray(); definedClass = defineClass(refField.getDeclaringClass().getClassLoader(), className, b); } Constructor ctor = definedClass.getConstructor(Field.class); return (ReflectionField) ctor.newInstance(refField); } catch (Exception e) { NoSuchFieldException err = new NoSuchFieldException( "Can't create ASM field reflection helper for [" + refField + "]"); err.initCause(e); throw err; } }
From source file:org.elasticsearch.painless.node.SSource.java
License:Apache License
public void write() { // Create the ClassWriter. int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS; int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL; String classBase = BASE_CLASS_TYPE.getInternalName(); String className = CLASS_TYPE.getInternalName(); String classInterfaces[] = reserved.usesScore() ? new String[] { WriterConstants.NEEDS_SCORE_TYPE.getInternalName() } : null;/*from ww w . j ava 2s . c om*/ ClassWriter writer = new ClassWriter(classFrames); ClassVisitor visitor = writer; // if picky is enabled, turn on some checks. instead of VerifyError at the end, you get a helpful stacktrace. if (settings.isPicky()) { visitor = new SimpleChecksAdapter(visitor); } if (debugStream != null) { visitor = new TraceClassVisitor(visitor, debugStream, null); } visitor.visit(WriterConstants.CLASS_VERSION, classAccess, className, null, classBase, classInterfaces); visitor.visitSource(Location.computeSourceName(name, source), null); // Write the constructor: MethodWriter constructor = new MethodWriter(Opcodes.ACC_PUBLIC, CONSTRUCTOR, visitor, globals.getStatements(), settings); constructor.visitCode(); constructor.loadThis(); constructor.loadArgs(); constructor.invokeConstructor(org.objectweb.asm.Type.getType(Executable.class), CONSTRUCTOR); constructor.returnValue(); constructor.endMethod(); // Write the execute method: MethodWriter execute = new MethodWriter(Opcodes.ACC_PUBLIC, EXECUTE, visitor, globals.getStatements(), settings); execute.visitCode(); write(execute, globals); execute.endMethod(); // Write all functions: for (SFunction function : functions) { function.write(visitor, settings, globals); } // Write all synthetic functions. Note that this process may add more :) while (!globals.getSyntheticMethods().isEmpty()) { List<SFunction> current = new ArrayList<>(globals.getSyntheticMethods().values()); globals.getSyntheticMethods().clear(); for (SFunction function : current) { function.write(visitor, settings, globals); } } // Write the constants if (false == globals.getConstantInitializers().isEmpty()) { Collection<Constant> inits = globals.getConstantInitializers().values(); // Fields for (Constant constant : inits) { visitor.visitField(Opcodes.ACC_FINAL | Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, constant.name, constant.type.getDescriptor(), null, null).visitEnd(); } // Initialize the constants in a static initializer final MethodWriter clinit = new MethodWriter(Opcodes.ACC_STATIC, WriterConstants.CLINIT, visitor, globals.getStatements(), settings); clinit.visitCode(); for (Constant constant : inits) { constant.initializer.accept(clinit); clinit.putStatic(CLASS_TYPE, constant.name, constant.type); } clinit.returnValue(); clinit.endMethod(); } // End writing the class and store the generated bytes. visitor.visitEnd(); bytes = writer.toByteArray(); }
From source file:org.elasticsearch.painless.PainlessScriptEngine.java
License:Apache License
/** * Generates a stateful factory class that will return script instances. Acts as a middle man between * the {@link ScriptContext#factoryClazz} and the {@link ScriptContext#instanceClazz} when used so that * the stateless factory can be used for caching and the stateful factory can act as a cache for new * script instances. Uses the newInstance method from a {@link ScriptContext#statefulFactoryClazz} to * define the factory method to create new instances of the {@link ScriptContext#instanceClazz}. * @param loader The {@link ClassLoader} that is used to define the factory class and script class. * @param context The {@link ScriptContext}'s semantics are used to define the factory class. * @param <T> The factory class.//from ww w . j a v a 2s.co m * @return A factory class that will return script instances. */ private <T> Type generateStatefulFactory(Loader loader, ScriptContext<T> context, MainMethodReserved reserved) { int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS; int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_FINAL; String interfaceBase = Type.getType(context.statefulFactoryClazz).getInternalName(); String className = interfaceBase + "$StatefulFactory"; String classInterfaces[] = new String[] { interfaceBase }; ClassWriter writer = new ClassWriter(classFrames); writer.visit(WriterConstants.CLASS_VERSION, classAccess, className, null, OBJECT_TYPE.getInternalName(), classInterfaces); Method newFactory = null; for (Method method : context.factoryClazz.getMethods()) { if ("newFactory".equals(method.getName())) { newFactory = method; break; } } for (int count = 0; count < newFactory.getParameterTypes().length; ++count) { writer.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_FINAL, "$arg" + count, Type.getType(newFactory.getParameterTypes()[count]).getDescriptor(), null, null).visitEnd(); } org.objectweb.asm.commons.Method base = new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class).toMethodDescriptorString()); org.objectweb.asm.commons.Method init = new org.objectweb.asm.commons.Method("<init>", MethodType.methodType(void.class, newFactory.getParameterTypes()).toMethodDescriptorString()); GeneratorAdapter constructor = new GeneratorAdapter(Opcodes.ASM5, init, writer.visitMethod(Opcodes.ACC_PUBLIC, init.getName(), init.getDescriptor(), null, null)); constructor.visitCode(); constructor.loadThis(); constructor.invokeConstructor(OBJECT_TYPE, base); for (int count = 0; count < newFactory.getParameterTypes().length; ++count) { constructor.loadThis(); constructor.loadArg(count); constructor.putField(Type.getType(className), "$arg" + count, Type.getType(newFactory.getParameterTypes()[count])); } constructor.returnValue(); constructor.endMethod(); Method newInstance = null; for (Method method : context.statefulFactoryClazz.getMethods()) { if ("newInstance".equals(method.getName())) { newInstance = method; break; } } org.objectweb.asm.commons.Method instance = new org.objectweb.asm.commons.Method(newInstance.getName(), MethodType.methodType(newInstance.getReturnType(), newInstance.getParameterTypes()) .toMethodDescriptorString()); List<Class<?>> parameters = new ArrayList<>(Arrays.asList(newFactory.getParameterTypes())); parameters.addAll(Arrays.asList(newInstance.getParameterTypes())); org.objectweb.asm.commons.Method constru = new org.objectweb.asm.commons.Method("<init>", MethodType .methodType(void.class, parameters.toArray(new Class<?>[] {})).toMethodDescriptorString()); GeneratorAdapter adapter = new GeneratorAdapter(Opcodes.ASM5, instance, writer.visitMethod( Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL, instance.getName(), instance.getDescriptor(), null, null)); adapter.visitCode(); adapter.newInstance(WriterConstants.CLASS_TYPE); adapter.dup(); for (int count = 0; count < newFactory.getParameterTypes().length; ++count) { adapter.loadThis(); adapter.getField(Type.getType(className), "$arg" + count, Type.getType(newFactory.getParameterTypes()[count])); } adapter.loadArgs(); adapter.invokeConstructor(WriterConstants.CLASS_TYPE, constru); adapter.returnValue(); adapter.endMethod(); writeNeedsMethods(context.statefulFactoryClazz, writer, reserved); writer.visitEnd(); loader.defineFactory(className.replace('/', '.'), writer.toByteArray()); return Type.getType(className); }