net.bytebuddy.dynamic.ClassFileLocator Java Examples
The following examples show how to use
net.bytebuddy.dynamic.ClassFileLocator.
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: PluginEngineSourceInMemoryTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testOfTypes() throws Exception { Plugin.Engine.Source.Origin origin = Plugin.Engine.Source.InMemory.ofTypes(Foo.class).read(); try { assertThat(origin.getClassFileLocator().locate(Foo.class.getName()).isResolved(), is(true)); assertThat(origin.getClassFileLocator().locate(Foo.class.getName()).resolve(), is(ClassFileLocator.ForClassLoader.read(Foo.class))); assertThat(origin.getClassFileLocator().locate("qux.Baz").isResolved(), is(false)); assertThat(origin.getManifest(), nullValue(Manifest.class)); Iterator<Plugin.Engine.Source.Element> iterator = origin.iterator(); assertThat(iterator.hasNext(), is(true)); Plugin.Engine.Source.Element element = iterator.next(); assertThat(element.getName(), is(Foo.class.getName().replace('.', '/') + ".class")); assertThat(element.resolveAs(Object.class), nullValue(Object.class)); assertThat(StreamDrainer.DEFAULT.drain(element.getInputStream()), is(ClassFileLocator.ForClassLoader.read(Foo.class))); assertThat(iterator.hasNext(), is(false)); } finally { origin.close(); } }
Example #2
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testSimpleTransformationIgnoredByPlugin() throws Exception { Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class); Plugin plugin = eager ? new IgnoringPlugin() : new PreprocessingPlugin(new IgnoringPlugin()); Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class); Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory(); Plugin.Engine.Summary summary = new Plugin.Engine.Default() .with(listener) .with(ClassFileLocator.ForClassLoader.of(IgnoringPlugin.class.getClassLoader())) .with(dispatcherFactory) .apply(source, target, new Plugin.Factory.Simple(plugin)); ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap()); Class<?> type = classLoader.loadClass(Sample.class.getName()); assertThat(type.getDeclaredFields().length, is(0)); assertThat(summary.getTransformed().size(), is(0)); assertThat(summary.getFailed().size(), is(0)); assertThat(summary.getUnresolved().size(), is(0)); verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST); verify(listener).onDiscovery(Sample.class.getName()); verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), plugin); verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin)); verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class)); verifyNoMoreInteractions(listener); }
Example #3
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testSimpleTransformation() throws Exception { Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class); Plugin plugin = eager ? new SimplePlugin() : new PreprocessingPlugin(new SimplePlugin()); Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class); Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory(); Plugin.Engine.Summary summary = new Plugin.Engine.Default() .with(listener) .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader())) .with(dispatcherFactory) .apply(source, target, new Plugin.Factory.Simple(plugin)); ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap()); Class<?> type = classLoader.loadClass(Sample.class.getName()); assertThat(type.getDeclaredField(FOO).getType(), is((Object) Void.class)); assertThat(summary.getTransformed(), hasItems(TypeDescription.ForLoadedType.of(Sample.class))); assertThat(summary.getFailed().size(), is(0)); assertThat(summary.getUnresolved().size(), is(0)); verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST); verify(listener).onDiscovery(Sample.class.getName()); verify(listener).onTransformation(TypeDescription.ForLoadedType.of(Sample.class), plugin); verify(listener).onTransformation(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin)); verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class)); verifyNoMoreInteractions(listener); }
Example #4
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testResource() throws Exception { Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class); Plugin.Engine.Source source = new Plugin.Engine.Source.InMemory(Collections.singletonMap(FOO, new byte[]{1, 2, 3})); Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory(); Plugin.Engine.Summary summary = new Plugin.Engine.Default() .with(listener) .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader())) .with(dispatcherFactory) .apply(source, target, new Plugin.Factory.Simple(eager ? new SimplePlugin() : new PreprocessingPlugin(new SimplePlugin()))); assertThat(summary.getTransformed().size(), is(0)); assertThat(summary.getFailed().size(), is(0)); assertThat(summary.getUnresolved().size(), is(0)); verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST); verify(listener).onResource(FOO); verifyNoMoreInteractions(listener); }
Example #5
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testSimpleTransformationIgnoredByMatcher() throws Exception { Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class); Plugin plugin = eager ? new SimplePlugin() : new PreprocessingPlugin(new SimplePlugin()); Plugin.Engine.Source source = Plugin.Engine.Source.InMemory.ofTypes(Sample.class); Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory(); Plugin.Engine.Summary summary = new Plugin.Engine.Default() .with(listener) .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader())) .with(dispatcherFactory) .ignore(ElementMatchers.is(Sample.class)) .apply(source, target, new Plugin.Factory.Simple(plugin)); ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, target.toTypeMap()); Class<?> type = classLoader.loadClass(Sample.class.getName()); assertThat(type.getDeclaredFields().length, is(0)); assertThat(summary.getTransformed().size(), is(0)); assertThat(summary.getFailed().size(), is(0)); assertThat(summary.getUnresolved().size(), is(0)); verify(listener).onManifest(Plugin.Engine.Source.Origin.NO_MANIFEST); verify(listener).onDiscovery(Sample.class.getName()); verify(listener).onIgnored(TypeDescription.ForLoadedType.of(Sample.class), Collections.singletonList(plugin)); verify(listener).onComplete(TypeDescription.ForLoadedType.of(Sample.class)); verifyNoMoreInteractions(listener); }
Example #6
Source File: Plugin.java From byte-buddy with Apache License 2.0 | 6 votes |
/** * Creates a new default plugin engine. * * @param byteBuddy The Byte Buddy instance to use. * @param typeStrategy The type strategy to use. * @param poolStrategy The pool strategy to use. * @param classFileLocator The class file locator to use. * @param listener The listener to use. * @param errorHandler The error handler to use. * @param dispatcherFactory The dispatcher factory to use. * @param ignoredTypeMatcher A matcher for types to exclude from transformation. */ protected Default(ByteBuddy byteBuddy, TypeStrategy typeStrategy, PoolStrategy poolStrategy, ClassFileLocator classFileLocator, Listener listener, ErrorHandler errorHandler, Dispatcher.Factory dispatcherFactory, ElementMatcher.Junction<? super TypeDescription> ignoredTypeMatcher) { this.byteBuddy = byteBuddy; this.typeStrategy = typeStrategy; this.poolStrategy = poolStrategy; this.classFileLocator = classFileLocator; this.listener = listener; this.errorHandler = errorHandler; this.dispatcherFactory = dispatcherFactory; this.ignoredTypeMatcher = ignoredTypeMatcher; }
Example #7
Source File: AgentBuilderDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Before @SuppressWarnings("unchecked") public void setUp() throws Exception { when(builder.make(TypeResolutionStrategy.Disabled.INSTANCE, typePool)).thenReturn((DynamicType.Unloaded) dynamicType); when(dynamicType.getTypeDescription()).thenReturn(TypeDescription.ForLoadedType.of(REDEFINED)); when(typeStrategy.builder(any(TypeDescription.class), eq(byteBuddy), any(ClassFileLocator.class), any(MethodNameTransformer.class), Mockito.<ClassLoader>any(), Mockito.<JavaModule>any(), Mockito.<ProtectionDomain>any())).thenReturn((DynamicType.Builder) builder); Map<TypeDescription, LoadedTypeInitializer> loadedTypeInitializers = new HashMap<TypeDescription, LoadedTypeInitializer>(); loadedTypeInitializers.put(TypeDescription.ForLoadedType.of(REDEFINED), loadedTypeInitializer); when(dynamicType.getLoadedTypeInitializers()).thenReturn(loadedTypeInitializers); when(dynamicType.getBytes()).thenReturn(BAZ); when(transformer.transform(builder, TypeDescription.ForLoadedType.of(REDEFINED), REDEFINED.getClassLoader(), JavaModule.ofType(REDEFINED))) .thenReturn((DynamicType.Builder) builder); when(poolStrategy.typePool(any(ClassFileLocator.class), any(ClassLoader.class))).thenReturn(typePool); when(typePool.describe(REDEFINED.getName())).thenReturn(resolution); when(instrumentation.getAllLoadedClasses()).thenReturn(new Class<?>[]{REDEFINED}); when(initializationStrategy.dispatcher()).thenReturn(dispatcher); when(dispatcher.apply(builder)).thenReturn((DynamicType.Builder) builder); }
Example #8
Source File: AbstractDynamicTypeBuilderForInliningTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testEnabledAnnotationRetention() throws Exception { Class<?> type = create(Annotated.class) .field(ElementMatchers.any()).annotateField(new Annotation[0]) .method(ElementMatchers.any()).intercept(StubMethod.INSTANCE) .make() .load(new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(SampleAnnotation.class)), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); @SuppressWarnings("unchecked") Class<? extends Annotation> sampleAnnotation = (Class<? extends Annotation>) type.getClassLoader().loadClass(SampleAnnotation.class.getName()); assertThat(type.isAnnotationPresent(sampleAnnotation), is(true)); assertThat(type.getDeclaredField(FOO).isAnnotationPresent(sampleAnnotation), is(true)); assertThat(type.getDeclaredMethod(FOO, Void.class).isAnnotationPresent(sampleAnnotation), is(true)); assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0].length, is(1)); assertThat(type.getDeclaredMethod(FOO, Void.class).getParameterAnnotations()[0][0].annotationType(), is((Object) sampleAnnotation)); }
Example #9
Source File: BootstrapInstrumentBoost.java From skywalking with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: ClassInjectorUsingReflectionTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test @ClassReflectionInjectionAvailableRule.Enforce public void testUnsafeOverride() throws Exception { ClassInjector.UsingReflection.Dispatcher dispatcher = ClassInjector.UsingReflection.Dispatcher.UsingUnsafeOverride.make().initialize(); assertThat(dispatcher.getPackage(classLoader, Foo.class.getPackage().getName()), nullValue(Package.class)); assertThat(dispatcher.definePackage(classLoader, Foo.class.getPackage().getName(), null, null, null, null, null, null, null), notNullValue(Package.class)); assertThat(dispatcher.findClass(classLoader, Foo.class.getName()), nullValue(Class.class)); assertThat(dispatcher.defineClass(classLoader, Foo.class.getName(), ClassFileLocator.ForClassLoader.read(Foo.class), null), notNullValue(Class.class)); assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader)); }
Example #11
Source File: EnhancerImpl.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Performs the enhancement. * * @param className The name of the class whose bytecode is being enhanced. * @param originalBytes The class's original (pre-enhancement) byte code * * @return The enhanced bytecode. Could be the same as the original bytecode if the original was * already enhanced or we could not enhance it for some reason. * * @throws EnhancementException Indicates a problem performing the enhancement */ @Override public synchronized byte[] enhance(String className, byte[] originalBytes) throws EnhancementException { //Classpool#describe does not accept '/' in the description name as it expects a class name. See HHH-12545 final String safeClassName = className.replace( '/', '.' ); try { final TypeDescription typeDescription = typePool.describe( safeClassName ).resolve(); return byteBuddyState.rewrite( typePool, safeClassName, originalBytes, byteBuddy -> doEnhance( byteBuddy.ignore( isDefaultFinalizer() ).redefine( typeDescription, ClassFileLocator.Simple.of( safeClassName, originalBytes ) ), typeDescription ) ); } catch (RuntimeException e) { throw new EnhancementException( "Failed to enhance class " + className, e ); } }
Example #12
Source File: PluginEngineDefaultTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testManifest() throws Exception { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); manifest.write(outputStream); Plugin.Engine.Listener listener = mock(Plugin.Engine.Listener.class); Plugin.Engine.Source source = new Plugin.Engine.Source.InMemory(Collections.singletonMap(JarFile.MANIFEST_NAME, outputStream.toByteArray())); Plugin.Engine.Target.InMemory target = new Plugin.Engine.Target.InMemory(); Plugin.Engine.Summary summary = new Plugin.Engine.Default() .with(listener) .with(ClassFileLocator.ForClassLoader.of(SimplePlugin.class.getClassLoader())) .with(dispatcherFactory) .apply(source, target, new Plugin.Factory.Simple(eager ? new SimplePlugin() : new PreprocessingPlugin(new SimplePlugin()))); assertThat(summary.getTransformed().size(), is(0)); assertThat(summary.getFailed().size(), is(0)); assertThat(summary.getUnresolved().size(), is(0)); verify(listener).onManifest(manifest); verifyNoMoreInteractions(listener); }
Example #13
Source File: RebaseDynamicTypeBuilderTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testPackageRebasement() throws Exception { Class<?> packageType = new ByteBuddy() .rebase(Sample.class.getPackage(), ClassFileLocator.ForClassLoader.of(getClass().getClassLoader())) .annotateType(AnnotationDescription.Builder.ofType(Baz.class).build()) .make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST) .getLoaded(); assertThat(packageType.getSimpleName(), CoreMatchers.is(PackageDescription.PACKAGE_CLASS_NAME)); assertThat(packageType.getName(), CoreMatchers.is(Sample.class.getPackage().getName() + "." + PackageDescription.PACKAGE_CLASS_NAME)); assertThat(packageType.getModifiers(), CoreMatchers.is(PackageDescription.PACKAGE_MODIFIERS)); assertThat(packageType.getDeclaredFields().length, CoreMatchers.is(0)); assertThat(packageType.getDeclaredMethods().length, CoreMatchers.is(0)); assertThat(packageType.getDeclaredAnnotations().length, CoreMatchers.is(2)); assertThat(packageType.getAnnotation(PackageAnnotation.class), notNullValue(PackageAnnotation.class)); assertThat(packageType.getAnnotation(Baz.class), notNullValue(Baz.class)); }
Example #14
Source File: ClassInjectorUsingReflectionTest.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test @ClassReflectionInjectionAvailableRule.Enforce @JavaVersionRule.Enforce(atMost = 10) public void testUnsafeInjection() throws Exception { ClassInjector.UsingReflection.Dispatcher dispatcher = ClassInjector.UsingReflection.Dispatcher.UsingUnsafeInjection.make().initialize(); assertThat(dispatcher.getPackage(classLoader, Foo.class.getPackage().getName()), nullValue(Package.class)); assertThat(dispatcher.definePackage(classLoader, Foo.class.getPackage().getName(), null, null, null, null, null, null, null), notNullValue(Package.class)); assertThat(dispatcher.findClass(classLoader, Foo.class.getName()), nullValue(Class.class)); assertThat(dispatcher.defineClass(classLoader, Foo.class.getName(), ClassFileLocator.ForClassLoader.read(Foo.class), null), notNullValue(Class.class)); assertThat(classLoader.loadClass(Foo.class.getName()).getClassLoader(), is(classLoader)); }
Example #15
Source File: AgentBuilderDefaultApplicationRedefinitionReiterationTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(AgentBuilderDefaultApplicationRedefinitionReiterationTest.class, Foo.class, Bar.class), ByteArrayClassLoader.PersistenceHandler.MANIFEST); }
Example #16
Source File: TypePoolLazyFacadeTypeDescriptionTest.java From byte-buddy with Apache License 2.0 | 5 votes |
protected TypeDescription describe(Class<?> type) { TypePool typePool = new TypePool.LazyFacade(new TypePool.Default(TypePool.CacheProvider.NoOp.INSTANCE, ClassFileLocator.ForClassLoader.of(type.getClassLoader()), TypePool.Default.ReaderMode.EXTENDED)); try { return typePool.describe(type.getName()).resolve(); } finally { typePool.clear(); } }
Example #17
Source File: RebaseDynamicTypeBuilder.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * Creates a rebase dynamic type builder. * * @param instrumentedType An instrumented type representing the subclass. * @param classFileVersion The class file version to use for types that are not based on an existing class file. * @param auxiliaryTypeNamingStrategy The naming strategy to use for naming auxiliary types. * @param annotationValueFilterFactory The annotation value filter factory to use. * @param annotationRetention The annotation retention strategy to use. * @param implementationContextFactory The implementation context factory to use. * @param methodGraphCompiler The method graph compiler to use. * @param typeValidation Determines if a type should be explicitly validated. * @param visibilityBridgeStrategy The visibility bridge strategy to apply. * @param classWriterStrategy The class writer strategy to use. * @param ignoredMethods A matcher for identifying methods that should be excluded from instrumentation. * @param originalType The original type that is being redefined or rebased. * @param classFileLocator The class file locator for locating the original type's class file. * @param methodNameTransformer The method rebase resolver to use for determining the name of a rebased method. */ public RebaseDynamicTypeBuilder(InstrumentedType.WithFlexibleName instrumentedType, ClassFileVersion classFileVersion, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, AnnotationValueFilter.Factory annotationValueFilterFactory, AnnotationRetention annotationRetention, Implementation.Context.Factory implementationContextFactory, MethodGraph.Compiler methodGraphCompiler, TypeValidation typeValidation, VisibilityBridgeStrategy visibilityBridgeStrategy, ClassWriterStrategy classWriterStrategy, LatentMatcher<? super MethodDescription> ignoredMethods, TypeDescription originalType, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer) { this(instrumentedType, new FieldRegistry.Default(), new MethodRegistry.Default(), new RecordComponentRegistry.Default(), annotationRetention.isEnabled() ? new TypeAttributeAppender.ForInstrumentedType.Differentiating(originalType) : TypeAttributeAppender.ForInstrumentedType.INSTANCE, AsmVisitorWrapper.NoOp.INSTANCE, classFileVersion, auxiliaryTypeNamingStrategy, annotationValueFilterFactory, annotationRetention, implementationContextFactory, methodGraphCompiler, typeValidation, visibilityBridgeStrategy, classWriterStrategy, ignoredMethods, Collections.<DynamicType>emptyList(), originalType, classFileLocator, methodNameTransformer); }
Example #18
Source File: DecoratingDynamicTypeBuilder.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * Creates a new decorating dynamic type builder. * * @param instrumentedType The instrumented type to decorate. * @param typeAttributeAppender The type attribute appender to apply onto the instrumented type. * @param asmVisitorWrapper The ASM visitor wrapper to apply onto the class writer. * @param classFileVersion The class file version to define auxiliary types in. * @param auxiliaryTypeNamingStrategy The naming strategy for auxiliary types to apply. * @param annotationValueFilterFactory The annotation value filter factory to apply. * @param annotationRetention The annotation retention to apply. * @param implementationContextFactory The implementation context factory to apply. * @param methodGraphCompiler The method graph compiler to use. * @param typeValidation Determines if a type should be explicitly validated. * @param classWriterStrategy The class writer strategy to use. * @param ignoredMethods A matcher for identifying methods that should be excluded from instrumentation. * @param auxiliaryTypes A list of explicitly required auxiliary types. * @param classFileLocator The class file locator for locating the original type's class file. */ protected DecoratingDynamicTypeBuilder(TypeDescription instrumentedType, TypeAttributeAppender typeAttributeAppender, AsmVisitorWrapper asmVisitorWrapper, ClassFileVersion classFileVersion, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, AnnotationValueFilter.Factory annotationValueFilterFactory, AnnotationRetention annotationRetention, Implementation.Context.Factory implementationContextFactory, MethodGraph.Compiler methodGraphCompiler, TypeValidation typeValidation, ClassWriterStrategy classWriterStrategy, LatentMatcher<? super MethodDescription> ignoredMethods, List<DynamicType> auxiliaryTypes, ClassFileLocator classFileLocator) { this.instrumentedType = instrumentedType; this.typeAttributeAppender = typeAttributeAppender; this.asmVisitorWrapper = asmVisitorWrapper; this.classFileVersion = classFileVersion; this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy; this.annotationValueFilterFactory = annotationValueFilterFactory; this.annotationRetention = annotationRetention; this.implementationContextFactory = implementationContextFactory; this.methodGraphCompiler = methodGraphCompiler; this.typeValidation = typeValidation; this.classWriterStrategy = classWriterStrategy; this.ignoredMethods = ignoredMethods; this.auxiliaryTypes = auxiliaryTypes; this.classFileLocator = classFileLocator; }
Example #19
Source File: TypePoolDefaultMethodDescriptionTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Before @Override public void setUp() throws Exception { super.setUp(); typePool = new TypePool.Default(TypePool.CacheProvider.NoOp.INSTANCE, ClassFileLocator.ForClassLoader.ofSystemLoader(), TypePool.Default.ReaderMode.EXTENDED); // In order to allow debug information parsing. }
Example #20
Source File: ToStringPluginTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test public void testPluginEnhanceIgnore() throws Exception { Class<?> type = new ToStringPlugin() .apply(new ByteBuddy().redefine(IgnoredFieldSample.class), TypeDescription.ForLoadedType.of(IgnoredFieldSample.class), ClassFileLocator.ForClassLoader.of(IgnoredFieldSample.class.getClassLoader())) .make() .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); Object instance = type.getDeclaredConstructor().newInstance(); type.getDeclaredField(FOO).set(instance, FOO); assertThat(instance.toString(), is("IgnoredFieldSample{}")); }
Example #21
Source File: AgentBuilderClassFileBufferStrategyTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test public void testDiscardingClassFileBufferStrategy() throws Exception { ClassFileLocator classFileLocator = AgentBuilder.ClassFileBufferStrategy.Default.DISCARDING.resolve("foo", new byte[]{123}, mock(ClassLoader.class), mock(JavaModule.class), mock(ProtectionDomain.class)); assertThat(classFileLocator.locate("foo").isResolved(), is(false)); assertThat(classFileLocator.locate("bar").isResolved(), is(false)); }
Example #22
Source File: HashCodeAndEqualsPlugin.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassFileLocator classFileLocator) { Enhance enhance = typeDescription.getDeclaredAnnotations().ofType(Enhance.class).load(); if (typeDescription.getDeclaredMethods().filter(isHashCode()).isEmpty()) { builder = builder.method(isHashCode()).intercept(enhance.invokeSuper() .hashCodeMethod(typeDescription) .withIgnoredFields(enhance.includeSyntheticFields() ? ElementMatchers.<FieldDescription>none() : ElementMatchers.<FieldDescription>isSynthetic()) .withIgnoredFields(new ValueMatcher(ValueHandling.Sort.IGNORE)) .withNonNullableFields(nonNullable(new ValueMatcher(ValueHandling.Sort.REVERSE_NULLABILITY)))); } if (typeDescription.getDeclaredMethods().filter(isEquals()).isEmpty()) { EqualsMethod equalsMethod = enhance.invokeSuper() .equalsMethod(typeDescription) .withIgnoredFields(enhance.includeSyntheticFields() ? ElementMatchers.<FieldDescription>none() : ElementMatchers.<FieldDescription>isSynthetic()) .withIgnoredFields(new ValueMatcher(ValueHandling.Sort.IGNORE)) .withNonNullableFields(nonNullable(new ValueMatcher(ValueHandling.Sort.REVERSE_NULLABILITY))) .withFieldOrder(AnnotationOrderComparator.INSTANCE); if (enhance.simpleComparisonsFirst()) { equalsMethod = equalsMethod .withPrimitiveTypedFieldsFirst() .withEnumerationTypedFieldsFirst() .withPrimitiveWrapperTypedFieldsFirst() .withStringTypedFieldsFirst(); } builder = builder.method(isEquals()).intercept(enhance.permitSubclassEquality() ? equalsMethod.withSubclassEquality() : equalsMethod); } return builder; }
Example #23
Source File: CachedReturnPlugin.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ public DynamicType.Builder<?> apply(DynamicType.Builder<?> builder, TypeDescription typeDescription, ClassFileLocator classFileLocator) { for (MethodDescription.InDefinedShape methodDescription : typeDescription.getDeclaredMethods() .filter(not(isBridge()).<MethodDescription>and(isAnnotatedWith(Enhance.class)))) { if (methodDescription.isAbstract()) { throw new IllegalStateException("Cannot cache the value of an abstract method: " + methodDescription); } else if (!methodDescription.getParameters().isEmpty()) { throw new IllegalStateException("Cannot cache the value of a method with parameters: " + methodDescription); } else if (methodDescription.getReturnType().represents(void.class)) { throw new IllegalStateException("Cannot cache void result for " + methodDescription); } String name = methodDescription.getDeclaredAnnotations().ofType(Enhance.class).load().value(); if (name.length() == 0) { name = methodDescription.getName() + NAME_INFIX + randomString.nextString(); } builder = builder .defineField(name, methodDescription.getReturnType().asErasure(), methodDescription.isStatic() ? Ownership.STATIC : Ownership.MEMBER, Visibility.PRIVATE, SyntheticState.SYNTHETIC, FieldPersistence.TRANSIENT) .visit(Advice.withCustomMapping() .bind(CacheField.class, new CacheFieldOffsetMapping(name)) .to(adviceByType.get(methodDescription.getReturnType().isPrimitive() ? methodDescription.getReturnType().asErasure() : TypeDescription.OBJECT), this.classFileLocator) .on(is(methodDescription))); } return builder; }
Example #24
Source File: AgentBuilderTransformerForBuildPluginTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test @SuppressWarnings("unchecked") public void testApplication() throws Exception { when(plugin.apply(eq(builder), eq(typeDescription), any(ClassFileLocator.ForClassLoader.class))).thenReturn((DynamicType.Builder) result); assertThat(new AgentBuilder.Transformer.ForBuildPlugin(plugin).transform(builder, typeDescription, classLoader, module), is((DynamicType.Builder) result)); verify(plugin).apply(eq(builder), eq(typeDescription), any(ClassFileLocator.ForClassLoader.class)); verifyNoMoreInteractions(plugin); }
Example #25
Source File: Plugin.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ public Engine with(ClassFileLocator classFileLocator) { return new Default(byteBuddy, typeStrategy, poolStrategy, new ClassFileLocator.Compound(this.classFileLocator, classFileLocator), listener, errorHandler, dispatcherFactory, ignoredTypeMatcher); }
Example #26
Source File: Plugin.java From byte-buddy with Apache License 2.0 | 5 votes |
/** * Represents a collection of types as a in-memory source. * * @param types The types to represent. * @return A source representing the supplied types. */ public static Source ofTypes(Collection<? extends Class<?>> types) { Map<TypeDescription, byte[]> binaryRepresentations = new HashMap<TypeDescription, byte[]>(); for (Class<?> type : types) { binaryRepresentations.put(TypeDescription.ForLoadedType.of(type), ClassFileLocator.ForClassLoader.read(type)); } return ofTypes(binaryRepresentations); }
Example #27
Source File: HashCodeAndEqualsPluginTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test(expected = NullPointerException.class) public void testPluginEnhanceNonNullableReversedHashCode() throws Exception { new HashCodeAndEqualsPlugin.WithNonNullableFields() .apply(new ByteBuddy().redefine(SimpleSample.class), TypeDescription.ForLoadedType.of(SimpleSample.class), ClassFileLocator.ForClassLoader.of(SimpleSample.class.getClassLoader())) .make() .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER) .getLoaded() .getDeclaredConstructor() .newInstance() .hashCode(); }
Example #28
Source File: ByteArrayClassLoaderPackageLookupStrategy.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test public void testGetPackage() throws Exception { ByteArrayClassLoader byteArrayClassLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(Foo.class)); byteArrayClassLoader.loadClass(Foo.class.getName()); assertThat(ByteArrayClassLoader.PackageLookupStrategy.ForLegacyVm.INSTANCE.apply(byteArrayClassLoader, Foo.class.getPackage().getName()).getName(), is(Foo.class.getPackage().getName())); }
Example #29
Source File: ClassInjectorUsingReflectionTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test @ClassReflectionInjectionAvailableRule.Enforce public void testInjectionOrderNoPrematureAuxiliaryInjection() throws Exception { ClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassFileLocator.ForClassLoader.readToNames(Bar.class, Interceptor.class)); Class<?> type = new ByteBuddy() .rebase(Bar.class) .method(named(BAR)) .intercept(MethodDelegation.to(Interceptor.class)).make() .load(classLoader, ClassLoadingStrategy.Default.INJECTION) .getLoaded(); assertThat(type.getDeclaredMethod(BAR, String.class).invoke(type.getDeclaredConstructor().newInstance(), FOO), is((Object) BAR)); }
Example #30
Source File: AbstractDynamicTypeBuilderForInliningTest.java From byte-buddy with Apache License 2.0 | 5 votes |
@Test public void testNoVisibilityBridgeForNonPublicType() throws Exception { InjectionClassLoader classLoader = new ByteArrayClassLoader(ClassLoadingStrategy.BOOTSTRAP_LOADER, false, ClassFileLocator.ForClassLoader.readToNames(PackagePrivateVisibilityBridgeExtension.class, VisibilityBridge.class, FooBar.class)); Class<?> type = create(PackagePrivateVisibilityBridgeExtension.class) .modifiers(0) .make() .load(classLoader, InjectionClassLoader.Strategy.INSTANCE) .getLoaded(); assertThat(type.getDeclaredConstructors().length, is(1)); assertThat(type.getDeclaredMethods().length, is(0)); }