Java Code Examples for net.bytebuddy.pool.TypePool

The following examples show how to use net.bytebuddy.pool.TypePool. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: lams   Author: lamsfoundation   File: PersistentAttributeTransformer.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static PersistentAttributeTransformer collectPersistentFields(
		TypeDescription managedCtClass,
		ByteBuddyEnhancementContext enhancementContext,
		TypePool classPool) {
	List<FieldDescription> persistentFieldList = new ArrayList<FieldDescription>();
	for ( FieldDescription ctField : managedCtClass.getDeclaredFields() ) {
		// skip static fields and skip fields added by enhancement and  outer reference in inner classes
		if ( ctField.getName().startsWith( "$$_hibernate_" ) || "this$0".equals( ctField.getName() ) ) {
			continue;
		}
		if ( !ctField.isStatic() && enhancementContext.isPersistentField( ctField ) ) {
			persistentFieldList.add( ctField );
		}
	}
	// HHH-10646 Add fields inherited from @MappedSuperclass
	// HHH-10981 There is no need to do it for @MappedSuperclass
	if ( !enhancementContext.isMappedSuperclassClass( managedCtClass ) ) {
		persistentFieldList.addAll( collectInheritPersistentFields( managedCtClass, enhancementContext ) );
	}

	FieldDescription[] orderedFields = enhancementContext.order( persistentFieldList.toArray( new FieldDescription[0] ) );
	log.debugf( "Persistent fields for entity %s: %s", managedCtClass.getName(), Arrays.toString( orderedFields ) );
	return new PersistentAttributeTransformer( managedCtClass, enhancementContext, classPool, orderedFields );
}
 
Example #2
Source Project: Diorite   Author: Diorite   File: TransformerInvokerGenerator.java    License: MIT License 6 votes vote down vote up
@Override
        public ClassVisitor wrap(TypeDescription typeDescription, ClassVisitor cv, Context context, TypePool typePool,
                                 FieldList<FieldDescription.InDefinedShape> fieldList, MethodList<?> methodList, int i, int i1)
        {
//            public void visit(int version, int modifiers, String name, String signature, String superName, String[] interfaces) {
            cv.visit(ClassFileVersion.JAVA_V9.getMinorMajorVersion(), typeDescription.getModifiers(), typeDescription.getInternalName(), null,
                     typeDescription.getSuperClass().asErasure().getInternalName(), typeDescription.getInterfaces().asErasures().toInternalNames());
            TypeDescription clazz = this.clazz;
            String internalName = clazz.getInternalName();
            String descriptor = clazz.getDescriptor();
            MethodList<InDefinedShape> declaredMethods = clazz.getDeclaredMethods();
            int methodsSize = declaredMethods.size();
            String implName = GENERATED_PREFIX + "." + clazz.getName();
            String internalImplName = GENERATED_PREFIX.replace('.', '/') + "/" + internalName;
            String descriptorImplName = "L" + GENERATED_PREFIX.replace('.', '/') + "/" + internalName + ";";

            FieldVisitor fv;
            MethodVisitor mv;
            AnnotationVisitor av0;

            cv.visitEnd();
            return cv;
        }
 
Example #3
Source Project: skywalking   Author: apache   File: BootstrapInstrumentBoost.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate the delegator class based on given template class. This is preparation stage level code generation.
 * <p>
 * One key step to avoid class confliction between AppClassLoader and BootstrapClassLoader
 *
 * @param classesTypeMap    hosts injected binary of generated class
 * @param typePool          to generate new class
 * @param templateClassName represents the class as template in this generation process. The templates are
 *                          pre-defined in SkyWalking agent core.
 */
private static void generateDelegator(Map<String, byte[]> classesTypeMap, TypePool typePool,
    String templateClassName, String methodsInterceptor) {
    String internalInterceptorName = internalDelegate(methodsInterceptor);
    try {
        TypeDescription templateTypeDescription = typePool.describe(templateClassName).resolve();

        DynamicType.Unloaded interceptorType = new ByteBuddy().redefine(templateTypeDescription, ClassFileLocator.ForClassLoader
            .of(BootstrapInstrumentBoost.class.getClassLoader()))
                                                              .name(internalInterceptorName)
                                                              .field(named("TARGET_INTERCEPTOR"))
                                                              .value(methodsInterceptor)
                                                              .make();

        classesTypeMap.put(internalInterceptorName, interceptorType.getBytes());

        InstrumentDebuggingClass.INSTANCE.log(interceptorType);
    } catch (Exception e) {
        throw new PluginException("Generate Dynamic plugin failure", e);
    }
}
 
Example #4
Source Project: byte-buddy   Author: raphw   File: MemberRemoval.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mappedFields = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mappedFields.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    Map<String, MethodDescription> mappedMethods = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mappedMethods.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new MemberRemovingClassVisitor(classVisitor, fieldMatcher, methodMatcher, mappedFields, mappedMethods);
}
 
Example #5
Source Project: byte-buddy   Author: raphw   File: ModifierAdjustment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ModifierAdjustingClassVisitor wrap(TypeDescription instrumentedType,
                                          ClassVisitor classVisitor,
                                          Implementation.Context implementationContext,
                                          TypePool typePool,
                                          FieldList<FieldDescription.InDefinedShape> fields,
                                          MethodList<?> methods,
                                          int writerFlags,
                                          int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mappedFields = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mappedFields.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    Map<String, MethodDescription> mappedMethods = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mappedMethods.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new ModifierAdjustingClassVisitor(classVisitor,
            typeAdjustments,
            fieldAdjustments,
            methodAdjustments,
            instrumentedType,
            mappedFields,
            mappedMethods);
}
 
Example #6
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    Map<String, MethodDescription> mapped = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mapped.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new DispatchingVisitor(classVisitor,
            instrumentedType,
            implementationContext,
            typePool,
            mapped,
            writerFlags,
            readerFlags);
}
 
Example #7
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodVisitor wrap(TypeDescription instrumentedType,
                          MethodDescription instrumentedMethod,
                          MethodVisitor methodVisitor,
                          Implementation.Context implementationContext,
                          TypePool typePool,
                          int writerFlags,
                          int readerFlags) {
    for (MethodVisitorWrapper methodVisitorWrapper : methodVisitorWrappers) {
        methodVisitor = methodVisitorWrapper.wrap(instrumentedType,
                instrumentedMethod,
                methodVisitor,
                implementationContext,
                typePool,
                writerFlags,
                readerFlags);
    }
    return methodVisitor;
}
 
Example #8
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new dispatching visitor.
 *
 * @param classVisitor          The underlying class visitor.
 * @param instrumentedType      The instrumented type.
 * @param implementationContext The implementation context to use.
 * @param typePool              The type pool to use.
 * @param methods               The methods that are declared by the instrumented type or virtually inherited.
 * @param writerFlags           The ASM {@link org.objectweb.asm.ClassWriter} flags to consider.
 * @param readerFlags           The ASM {@link org.objectweb.asm.ClassReader} flags to consider.
 */
protected DispatchingVisitor(ClassVisitor classVisitor,
                             TypeDescription instrumentedType,
                             Implementation.Context implementationContext,
                             TypePool typePool,
                             Map<String, MethodDescription> methods,
                             int writerFlags,
                             int readerFlags) {
    super(OpenedClassReader.ASM_API, classVisitor);
    this.instrumentedType = instrumentedType;
    this.implementationContext = implementationContext;
    this.typePool = typePool;
    this.methods = methods;
    this.writerFlags = writerFlags;
    this.readerFlags = readerFlags;
}
 
Example #9
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    for (AsmVisitorWrapper asmVisitorWrapper : asmVisitorWrappers) {
        classVisitor = asmVisitorWrapper.wrap(instrumentedType,
                classVisitor,
                implementationContext,
                typePool,
                fields,
                methods,
                writerFlags,
                readerFlags);
    }
    return classVisitor;
}
 
Example #10
Source Project: byte-buddy   Author: raphw   File: TypeConstantAdjustmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInstrumentationModernClassFile() throws Exception {
    ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap(mock(TypeDescription.class),
            this.classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED);
    classVisitor.visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    assertThat(classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ}), is(methodVisitor));
    verify(this.classVisitor).visit(ClassFileVersion.JAVA_V5.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verifyNoMoreInteractions(this.classVisitor);
    verifyZeroInteractions(methodVisitor);
}
 
Example #11
Source Project: byte-buddy   Author: raphw   File: MemberSubstitution.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new substituting method visitor.
 *
 * @param methodVisitor         The method visitor to delegate to.
 * @param instrumentedType      The instrumented type.
 * @param instrumentedMethod    The instrumented method.
 * @param methodGraphCompiler   The method graph compiler to use.
 * @param strict                {@code true} if the method processing should be strict where an exception is raised if a member cannot be found.
 * @param replacement           The replacement to use for creating substitutions.
 * @param implementationContext The implementation context to use.
 * @param typePool              The type pool to use.
 * @param virtualPrivateCalls   {@code true}, virtual method calls might target private methods in accordance to the nest mate specification.
 */
protected SubstitutingMethodVisitor(MethodVisitor methodVisitor,
                                    TypeDescription instrumentedType,
                                    MethodDescription instrumentedMethod,
                                    MethodGraph.Compiler methodGraphCompiler,
                                    boolean strict,
                                    Replacement replacement,
                                    Implementation.Context implementationContext,
                                    TypePool typePool,
                                    boolean virtualPrivateCalls) {
    super(methodVisitor, instrumentedMethod);
    this.instrumentedType = instrumentedType;
    this.instrumentedMethod = instrumentedMethod;
    this.methodGraphCompiler = methodGraphCompiler;
    this.strict = strict;
    this.replacement = replacement;
    this.implementationContext = implementationContext;
    this.typePool = typePool;
    this.virtualPrivateCalls = virtualPrivateCalls;
    stackSizeBuffer = 0;
    localVariableExtension = 0;
}
 
Example #12
Source Project: byte-buddy   Author: raphw   File: RedefinitionDynamicTypeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    MethodRegistry.Prepared methodRegistry = this.methodRegistry.prepare(instrumentedType,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            InliningImplementationMatcher.of(ignoredMethods, originalType));
    return TypeWriter.Default.<T>forRedefinition(methodRegistry,
            auxiliaryTypes,
            fieldRegistry.compile(methodRegistry.getInstrumentedType()),
            recordComponentRegistry.compile(methodRegistry.getInstrumentedType()),
            typeAttributeAppender,
            asmVisitorWrapper,
            classFileVersion,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool,
            originalType,
            classFileLocator).make(typeResolutionStrategy.resolve());
}
 
Example #13
Source Project: byte-buddy   Author: raphw   File: TypeConstantAdjustmentTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testInstrumentationLegacyClassFileObjectType() throws Exception {
    ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap(mock(TypeDescription.class),
            this.classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED);
    classVisitor.visit(ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    MethodVisitor methodVisitor = classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    assertThat(methodVisitor, not(this.methodVisitor));
    methodVisitor.visitLdcInsn(Type.getType(Object.class));
    verify(this.classVisitor).visit(ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[]{BAZ});
    verifyNoMoreInteractions(this.classVisitor);
    verify(this.methodVisitor).visitLdcInsn(Type.getType(Object.class).getClassName());
    verify(this.methodVisitor).visitMethodInsn(Opcodes.INVOKESTATIC,
            Type.getType(Class.class).getInternalName(),
            "forName",
            Type.getType(Class.class.getDeclaredMethod("forName", String.class)).getDescriptor(),
            false);
    verifyNoMoreInteractions(this.methodVisitor);
}
 
Example #14
Source Project: byte-buddy   Author: raphw   File: CachedReturnPlugin.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a plugin for caching method return values.
 */
public CachedReturnPlugin() {
    super(declaresMethod(isAnnotatedWith(Enhance.class)));
    randomString = new RandomString();
    classFileLocator = ClassFileLocator.ForClassLoader.of(CachedReturnPlugin.class.getClassLoader());
    TypePool typePool = TypePool.Default.of(classFileLocator);
    adviceByType = new HashMap<TypeDescription, TypeDescription>();
    for (Class<?> type : new Class<?>[]{
            boolean.class,
            byte.class,
            short.class,
            char.class,
            int.class,
            long.class,
            float.class,
            double.class,
            Object.class
    }) {
        adviceByType.put(TypeDescription.ForLoadedType.ForLoadedType.of(type), typePool.describe(CachedReturnPlugin.class.getName()
                + ADVICE_INFIX
                + type.getSimpleName()).resolve());
    }
}
 
Example #15
Source Project: byte-buddy   Author: raphw   File: SubclassDynamicTypeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    MethodRegistry.Compiled methodRegistry = constructorStrategy
            .inject(instrumentedType, this.methodRegistry)
            .prepare(applyConstructorStrategy(instrumentedType),
                methodGraphCompiler,
                typeValidation,
                visibilityBridgeStrategy,
                new InstrumentableMatcher(ignoredMethods))
            .compile(SubclassImplementationTarget.Factory.SUPER_CLASS, classFileVersion);
    return TypeWriter.Default.<T>forCreation(methodRegistry,
            auxiliaryTypes,
            fieldRegistry.compile(methodRegistry.getInstrumentedType()),
            recordComponentRegistry.compile(methodRegistry.getInstrumentedType()),
            typeAttributeAppender,
            asmVisitorWrapper,
            classFileVersion,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool).make(typeResolutionStrategy.resolve());
}
 
Example #16
Source Project: byte-buddy   Author: raphw   File: DecoratingDynamicTypeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType.Unloaded<T> make(TypeResolutionStrategy typeResolutionStrategy, TypePool typePool) {
    return TypeWriter.Default.<T>forDecoration(instrumentedType,
            classFileVersion,
            auxiliaryTypes,
            CompoundList.of(methodGraphCompiler.compile(instrumentedType)
                    .listNodes()
                    .asMethodList()
                    .filter(not(ignoredMethods.resolve(instrumentedType))), instrumentedType.getDeclaredMethods().filter(not(isVirtual()))),
            typeAttributeAppender,
            asmVisitorWrapper,
            annotationValueFilterFactory,
            annotationRetention,
            auxiliaryTypeNamingStrategy,
            implementationContextFactory,
            typeValidation,
            classWriterStrategy,
            typePool,
            classFileLocator).make(typeResolutionStrategy.resolve());
}
 
Example #17
Source Project: garmadon   Author: criteo   File: ClassFileExtraction.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] extract(Class<?> type, AsmVisitorWrapper asmVisitorWrapper) throws IOException {
    ClassReader classReader = new ClassReader(type.getName());
    ClassWriter classWriter = new ClassWriter(classReader, AsmVisitorWrapper.NO_FLAGS);
    classReader.accept(asmVisitorWrapper.wrap(new TypeDescription.ForLoadedType(type),
            classWriter,
            new IllegalContext(),
            TypePool.Empty.INSTANCE,
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            AsmVisitorWrapper.NO_FLAGS,
            AsmVisitorWrapper.NO_FLAGS), AsmVisitorWrapper.NO_FLAGS);
    return classWriter.toByteArray();
}
 
Example #18
Source Project: apm-agent-java   Author: elastic   File: SoftlyReferencingTypePoolCache.java    License: Apache License 2.0 5 votes vote down vote up
public SoftlyReferencingTypePoolCache(final TypePool.Default.ReaderMode readerMode,
                                      final int clearIfNotAccessedSinceMinutes, ElementMatcher.Junction<ClassLoader> ignoredClassLoaders) {
    super(readerMode);
    ExecutorUtils.createSingleThreadSchedulingDeamonPool("type-cache-pool-cleaner")
        .scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                clearIfNotAccessedSince(clearIfNotAccessedSinceMinutes);
                cacheProviders.expungeStaleEntries();
            }
        }, 1, 1, TimeUnit.MINUTES);
    this.ignoredClassLoaders = ignoredClassLoaders;
}
 
Example #19
Source Project: byte-buddy   Author: raphw   File: PluginEnginePoolStrategyTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEagerResolutionExtended() {
    assertThat(Plugin.Engine.PoolStrategy.Eager.EXTENDED.typePool(classFileLocator),
            hasPrototype((TypePool) new TypePool.Default(new TypePool.CacheProvider.Simple(),
                    classFileLocator,
                    TypePool.Default.ReaderMode.EXTENDED,
                    TypePool.ClassLoading.ofPlatformLoader())));
}
 
Example #20
Source Project: byte-buddy   Author: raphw   File: MemberSubstitutionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOptionalFieldRelaxed() throws Exception {
    assertThat(new ByteBuddy()
            .redefine(OptionalTarget.class)
            .visit(MemberSubstitution.relaxed().field(named(BAR)).stub().on(named(RUN)))
            .make(TypePool.Empty.INSTANCE), notNullValue(DynamicType.class));
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: PersistentAttributeTransformer.java    License: GNU General Public License v2.0 5 votes vote down vote up
private PersistentAttributeTransformer(
		TypeDescription managedCtClass,
		ByteBuddyEnhancementContext enhancementContext,
		TypePool classPool,
		FieldDescription[] enhancedFields) {
	this.managedCtClass = managedCtClass;
	this.enhancementContext = enhancementContext;
	this.classPool = classPool;
	this.enhancedFields = enhancedFields;
}
 
Example #22
Source Project: lams   Author: lamsfoundation   File: PersistentAttributeTransformer.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public MethodVisitor wrap(
		TypeDescription instrumentedType,
		MethodDescription instrumentedMethod,
		MethodVisitor methodVisitor,
		Implementation.Context implementationContext,
		TypePool typePool,
		int writerFlags,
		int readerFlags) {
	return new MethodVisitor( Opcodes.ASM5, methodVisitor ) {
		@Override
		public void visitFieldInsn(int opcode, String owner, String name, String desc) {
			if ( isEnhanced( owner, name, desc ) ) {
				switch ( opcode ) {
					case Opcodes.GETFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_READER_PREFIX + name,
								"()" + desc,
								false
						);
						return;
					case Opcodes.PUTFIELD:
						methodVisitor.visitMethodInsn(
								Opcodes.INVOKEVIRTUAL,
								owner,
								EnhancerConstants.PERSISTENT_FIELD_WRITER_PREFIX + name,
								"(" + desc + ")V",
								false
						);
						return;
				}
			}
			super.visitFieldInsn( opcode, owner, name, desc );
		}
	};
}
 
Example #23
Source Project: byte-buddy   Author: raphw   File: DecoratingDynamicTypeBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDecorationNonVirtualMember() throws Exception {
    Object instance = new ByteBuddy()
            .decorate(Foo.class)
            .annotateType(AnnotationDescription.Builder.ofType(Qux.class).build())
            .ignoreAlso(new LatentMatcher.Resolved<MethodDescription>(none()))
            .visit(new AsmVisitorWrapper.ForDeclaredMethods().method(named(BAR), new AsmVisitorWrapper.ForDeclaredMethods.MethodVisitorWrapper() {
                public MethodVisitor wrap(TypeDescription instrumentedType,
                                          MethodDescription instrumentedMethod,
                                          MethodVisitor methodVisitor,
                                          Implementation.Context implementationContext,
                                          TypePool typePool,
                                          int writerFlags,
                                          int readerFlags) {
                    return new MethodVisitor(OpenedClassReader.ASM_API, methodVisitor) {
                        @Override
                        public void visitLdcInsn(Object value) {
                            if (FOO.equals(value)) {
                                value = BAR;
                            }
                            super.visitLdcInsn(value);
                        }
                    };
                }
            }))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getConstructor()
            .newInstance();
    assertThat(instance.getClass().getMethod(BAR).invoke(null), is((Object) BAR));
    assertThat(instance.getClass().isAnnotationPresent(Bar.class), is(true));
    assertThat(instance.getClass().isAnnotationPresent(Qux.class), is(true));
}
 
Example #24
Source Project: lams   Author: lamsfoundation   File: ByteBuddyState.java    License: GNU General Public License v2.0 5 votes vote down vote up
private Unloaded<?> make(TypePool typePool, DynamicType.Builder<?> builder) {
	if ( System.getSecurityManager() != null ) {
		builder = builder.visit( getDeclaredMethodMemberSubstitution );
		builder = builder.visit( getMethodMemberSubstitution );
	}

	Unloaded<?> unloadedClass;
	if ( typePool != null ) {
		unloadedClass = builder.make( typePool );
	}
	else {
		unloadedClass = builder.make();
	}

	if ( DEBUG ) {
		try {
			unloadedClass.saveIn( new File( System.getProperty( "java.io.tmpdir" ) + "/bytebuddy/" ) );
		}
		catch (IOException e) {
			LOG.warn( "Unable to save generated class %1$s", unloadedClass.getTypeDescription().getName(), e );
		}
	}

	if ( System.getSecurityManager() != null ) {
		// we authorize the proxy class to access the method lookup dispatcher
		HibernateMethodLookupDispatcher.registerAuthorizedClass( unloadedClass.getTypeDescription().getName() );
	}

	return unloadedClass;
}
 
Example #25
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapperNoOpTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapperChain() throws Exception {
    ClassVisitor classVisitor = mock(ClassVisitor.class);
    assertThat(AsmVisitorWrapper.NoOp.INSTANCE.wrap(mock(TypeDescription.class),
            classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED), is(classVisitor));
    verifyZeroInteractions(classVisitor);
}
 
Example #26
Source Project: kanela   Author: kamon-io   File: ClassFileVersionValidatorWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ClassVisitor wrap(TypeDescription typeDescription,
                         ClassVisitor classVisitor,
                         Implementation.Context context,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fieldList, MethodList<?> methodList,
                         int writerFlags,
                         int readerFlags) {

    return ClassFileVersionValidatorClassVisitor.from(classVisitor);
}
 
Example #27
Source Project: kanela   Author: kamon-io   File: PoolStrategyCache.java    License: Apache License 2.0 5 votes vote down vote up
private PoolStrategyCache() {
    super(TypePool.Default.ReaderMode.FAST);
    ExpiringMap.setThreadFactory(NamedThreadFactory.instance("strategy-cache-listener"));
    this.cache = ExpiringMap
            .builder()
            .entryLoader((key) -> TypePool.CacheProvider.Simple.withObjectType())
            .expiration(1, TimeUnit.MINUTES)
            .expirationPolicy(ExpirationPolicy.ACCESSED)
            .asyncExpirationListener(LogExpirationListener())
            .build();
}
 
Example #28
Source Project: byte-buddy   Author: raphw   File: TypeReferenceAdjustmentTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRelaxedCannotFindType() {
    new ByteBuddy()
            .subclass(Foo.Bar.class)
            .visit(TypeReferenceAdjustment.relaxed())
            .make(TypePool.Empty.INSTANCE);
}
 
Example #29
Source Project: byte-buddy   Author: raphw   File: MemberAttributeExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodVisitor wrap(TypeDescription instrumentedType,
                          MethodDescription instrumentedMethod,
                          MethodVisitor methodVisitor,
                          Implementation.Context implementationContext,
                          TypePool typePool,
                          int writerFlags,
                          int readerFlags) {
    return new AttributeAppendingMethodVisitor(methodVisitor,
            instrumentedMethod,
            attributeAppenderFactory.make(instrumentedType),
            annotationValueFilterFactory.on(instrumentedMethod));
}
 
Example #30
Source Project: byte-buddy   Author: raphw   File: TypeReferenceAdjustmentTest.java    License: Apache License 2.0 5 votes vote down vote up
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    return new AssertionClassVisitor(classVisitor);
}