net.bytebuddy.pool.TypePool Java Examples

The following examples show how to use net.bytebuddy.pool.TypePool. 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 File: AsmVisitorWrapper.java    From byte-buddy with 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 #2
Source File: CachedReturnPlugin.java    From byte-buddy with 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 #3
Source File: TransformerInvokerGenerator.java    From Diorite with 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 #4
Source File: BootstrapInstrumentBoost.java    From skywalking with 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 #5
Source File: TypeConstantAdjustmentTest.java    From byte-buddy with 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 #6
Source File: PersistentAttributeTransformer.java    From lams with 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 #7
Source File: TypeConstantAdjustmentTest.java    From byte-buddy with 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 #8
Source File: MemberRemoval.java    From byte-buddy with 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 #9
Source File: AsmVisitorWrapper.java    From byte-buddy with 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 File: RedefinitionDynamicTypeBuilder.java    From byte-buddy with 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 #11
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with 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 #12
Source File: ModifierAdjustment.java    From byte-buddy with 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 #13
Source File: AsmVisitorWrapper.java    From byte-buddy with 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 #14
Source File: AsmVisitorWrapper.java    From byte-buddy with 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 #15
Source File: MemberSubstitution.java    From byte-buddy with 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 #16
Source File: SubclassDynamicTypeBuilder.java    From byte-buddy with 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 #17
Source File: ClassByExtensionBenchmark.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * A setup method to create precomputed delegator.
 */
@Setup
public void setup() {
    proxyInterceptor = MethodDelegation.to(ByteBuddyProxyInterceptor.class);
    accessInterceptor = MethodDelegation.to(ByteBuddyAccessInterceptor.class);
    prefixInterceptor = MethodDelegation.to(ByteBuddyPrefixInterceptor.class);
    baseClassDescription = TypePool.Default.ofSystemLoader().describe(baseClass.getName()).resolve();
    proxyClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyProxyInterceptor.class.getName()).resolve();
    accessClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyAccessInterceptor.class.getName()).resolve();
    prefixClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyPrefixInterceptor.class.getName()).resolve();
    proxyInterceptorDescription = MethodDelegation.to(proxyClassDescription);
    accessInterceptorDescription = MethodDelegation.to(accessClassDescription);
    prefixInterceptorDescription = MethodDelegation.to(prefixClassDescription);
}
 
Example #18
Source File: PluginEnginePoolStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithLazyResolutionExtended() {
    assertThat(Plugin.Engine.PoolStrategy.Default.EXTENDED.typePool(classFileLocator),
            hasPrototype((TypePool) new TypePool.Default.WithLazyResolution(new TypePool.CacheProvider.Simple(),
                    classFileLocator,
                    TypePool.Default.ReaderMode.EXTENDED,
                    TypePool.ClassLoading.ofPlatformLoader())));
}
 
Example #19
Source File: PluginEnginePoolStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithLazyResolutionFast() {
    assertThat(Plugin.Engine.PoolStrategy.Default.FAST.typePool(classFileLocator),
            hasPrototype((TypePool) new TypePool.Default.WithLazyResolution(new TypePool.CacheProvider.Simple(),
                    classFileLocator,
                    TypePool.Default.ReaderMode.FAST,
                    TypePool.ClassLoading.ofPlatformLoader())));
}
 
Example #20
Source File: Plugin.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Callable<Dispatcher.Materializable> call() throws Exception {
    listener.onDiscovery(typeName);
    TypePool.Resolution resolution = typePool.describe(typeName);
    if (resolution.isResolved()) {
        TypeDescription typeDescription = resolution.resolve();
        try {
            if (!ignoredTypeMatcher.matches(typeDescription)) {
                for (WithPreprocessor preprocessor : preprocessors) {
                    preprocessor.onPreprocess(typeDescription, classFileLocator);
                }
                return new Resolved(typeDescription);
            } else {
                return new Ignored(typeDescription);
            }
        } catch (Throwable throwable) {
            listener.onComplete(typeDescription);
            if (throwable instanceof Exception) {
                throw (Exception) throwable;
            } else if (throwable instanceof Error) {
                throw (Error) throwable;
            } else {
                throw new IllegalStateException(throwable);
            }
        }
    } else {
        return new Unresolved();
    }
}
 
Example #21
Source File: ClassFileExtraction.java    From garmadon with 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 #22
Source File: TypeReferenceAdjustment.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a type reference class visitor.
 *
 * @param classVisitor {@code true} if the visitor should throw an exception if a type reference cannot be located.
 * @param strict       {@code true} if the visitor should throw an exception if a type reference cannot be located.
 * @param filter       A filter for excluding types from type reference analysis.
 * @param typePool     The type pool to use for locating types.
 */
protected TypeReferenceClassVisitor(ClassVisitor classVisitor, boolean strict, ElementMatcher<? super TypeDescription> filter, TypePool typePool) {
    super(OpenedClassReader.ASM_API, classVisitor);
    this.typePool = typePool;
    this.strict = strict;
    this.filter = filter;
    observedTypes = new HashSet<String>();
    visitedInnerTypes = new HashSet<String>();
}
 
Example #23
Source File: MemberSubstitutionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testOptionalMethod() throws Exception {
    new ByteBuddy()
            .redefine(OptionalTarget.class)
            .visit(MemberSubstitution.strict().method(named(BAR)).stub().on(named(RUN)))
            .make(TypePool.Empty.INSTANCE);
}
 
Example #24
Source File: PluginEnginePoolStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithEagerResolutionFast() {
    assertThat(Plugin.Engine.PoolStrategy.Eager.FAST.typePool(classFileLocator),
            hasPrototype((TypePool) new TypePool.Default(new TypePool.CacheProvider.Simple(),
                    classFileLocator,
                    TypePool.Default.ReaderMode.FAST,
                    TypePool.ClassLoading.ofPlatformLoader())));
}
 
Example #25
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Replacement make(TypeDescription instrumentedType, MethodDescription instrumentedMethod, TypePool typePool) {
    List<Replacement> replacements = new ArrayList<Replacement>();
    for (Factory factory : factories) {
        replacements.add(factory.make(instrumentedType, instrumentedMethod, typePool));
    }
    return new ForFirstBinding(replacements);
}
 
Example #26
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Replacement make(TypeDescription instrumentedType, MethodDescription instrumentedMethod, TypePool typePool) {
    return new ForElementMatchers(fieldMatcher,
            methodMatcher,
            matchFieldRead,
            matchFieldWrite,
            includeVirtualCalls,
            includeSuperCalls,
            substitutionFactory.make(instrumentedType, instrumentedMethod, typePool));
}
 
Example #27
Source File: ClassWriterStrategyFrameComputingClassWriterTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    frameComputingClassWriter = new ClassWriterStrategy.FrameComputingClassWriter(mock(ClassReader.class), 0, typePool);
    when(typePool.describe(FOO.replace('/', '.'))).thenReturn(new TypePool.Resolution.Simple(leftType));
    when(typePool.describe(BAR.replace('/', '.'))).thenReturn(new TypePool.Resolution.Simple(rightType));
    when(leftType.getInternalName()).thenReturn(QUX);
    when(rightType.getInternalName()).thenReturn(BAZ);
    when(leftType.getSuperClass()).thenReturn(genericSuperClass);
    when(genericSuperClass.asErasure()).thenReturn(superClass);
    when(superClass.getInternalName()).thenReturn(FOOBAR);
}
 
Example #28
Source File: Plugin.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public TypePool typePool(ClassFileLocator classFileLocator) {
    return new TypePool.Default(new TypePool.CacheProvider.Simple(),
            classFileLocator,
            readerMode,
            TypePool.ClassLoading.ofPlatformLoader());
}
 
Example #29
Source File: AdviceTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAdviceNativeMethodIsSkipped() throws Exception {
    Advice.Dispatcher.Resolved.ForMethodEnter methodEnter = mock(Advice.Dispatcher.Resolved.ForMethodEnter.class);
    Advice.Dispatcher.Resolved.ForMethodExit methodExit = mock(Advice.Dispatcher.Resolved.ForMethodExit.class);
    MethodDescription.InDefinedShape methodDescription = mock(MethodDescription.InDefinedShape.class);
    when(methodDescription.isNative()).thenReturn(true);
    MethodVisitor methodVisitor = mock(MethodVisitor.class);
    assertThat(new Advice(methodEnter, methodExit).wrap(mock(TypeDescription.class),
            methodDescription,
            methodVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            IGNORED,
            IGNORED), sameInstance(methodVisitor));
}
 
Example #30
Source File: DebuggingWrapper.java    From byte-buddy with 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 check
            ? new CheckClassAdapter(new TraceClassVisitor(classVisitor, printer, printWriter))
            : new TraceClassVisitor(classVisitor, printer, printWriter);
}