net.bytebuddy.ClassFileVersion Java Examples

The following examples show how to use net.bytebuddy.ClassFileVersion. 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: AdviceJsrRetTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testJsrRetByteCodes() throws Exception {
    Class<?> type = new ByteBuddy(ClassFileVersion.JAVA_V4)
            .subclass(Object.class)
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new JsrRetMethod())
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER_PERSISTENT)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
    Class<?> advised = new ByteBuddy()
            .redefine(type)
            .visit(Advice.to(JsrAdvice.class).on(named(FOO)))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(advised.getDeclaredMethod(FOO).invoke(advised.getDeclaredConstructor().newInstance()), is((Object) BAR));
}
 
Example #2
Source File: TypeProxyCreationTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllIllegal() throws Exception {
    when(implementationTarget.getInstrumentedType()).thenReturn(foo);
    when(invocationFactory.invoke(eq(implementationTarget), eq(foo), any(MethodDescription.class)))
            .thenReturn(specialMethodInvocation);
    TypeDescription dynamicType = new TypeProxy(foo,
            implementationTarget,
            invocationFactory,
            true,
            false)
            .make(BAR, ClassFileVersion.ofThisVm(), methodAccessorFactory)
            .getTypeDescription();
    assertThat(dynamicType.getModifiers(), is(modifiers));
    assertThat(dynamicType.getSuperClass().asErasure(), is(foo));
    assertThat(dynamicType.getInterfaces(), is((TypeList.Generic) new TypeList.Generic.Empty()));
    assertThat(dynamicType.getName(), is(BAR));
    assertThat(dynamicType.getDeclaredMethods().size(), is(2));
    assertThat(dynamicType.isAssignableTo(Serializable.class), is(false));
    verifyZeroInteractions(methodAccessorFactory);
    for (MethodDescription methodDescription : fooMethods) {
        verify(invocationFactory).invoke(implementationTarget, foo, methodDescription);
    }
    verifyNoMoreInteractions(invocationFactory);
    verify(specialMethodInvocation, times(fooMethods.size())).isValid();
    verifyNoMoreInteractions(specialMethodInvocation);
}
 
Example #3
Source File: AbstractAnnotationDescriptionTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    first = FooSample.class.getAnnotation(Sample.class);
    second = BarSample.class.getAnnotation(Sample.class);
    defaultFirst = DefaultSample.class.getAnnotation(SampleDefault.class);
    defaultSecond = NonDefaultSample.class.getAnnotation(SampleDefault.class);
    explicitTarget = ExplicitTarget.Carrier.class.getAnnotation(ExplicitTarget.class);
    brokenCarrier = new ByteBuddy()
            .subclass(Object.class)
            .visit(new AnnotationValueBreaker(ClassFileVersion.ofThisVm().isAtLeast(ClassFileVersion.JAVA_V12), false))
            .make()
            .include(new ByteBuddy().subclass(Object.class).name(BrokenAnnotationProperty.class.getName()).make())
            .include(new ByteBuddy().subclass(Object.class).name(BrokenEnumerationProperty.class.getName()).make())
            .load(getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST_PERSISTENT)
            .getLoaded();
    broken = brokenCarrier.getAnnotations()[0];
}
 
Example #4
Source File: FieldConstantTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstantCreationModernVisible() throws Exception {
    when(classFileVersion.isAtLeast(ClassFileVersion.JAVA_V5)).thenReturn(true);
    when(declaringType.isVisibleTo(instrumentedType)).thenReturn(true);
    StackManipulation stackManipulation = new FieldConstant(fieldDescription);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(1));
    assertThat(size.getMaximalSize(), is(2));
    verify(methodVisitor).visitLdcInsn(Type.getObjectType(QUX));
    verify(methodVisitor).visitLdcInsn(BAR);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKEVIRTUAL,
            "java/lang/Class",
            "getDeclaredField",
            "(Ljava/lang/String;)Ljava/lang/reflect/Field;",
            false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #5
Source File: OpenedClassReader.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a class reader for the given binary representation of a class file.
 *
 * @param binaryRepresentation The binary representation of a class file to read.
 * @return An appropriate class reader.
 */
public static ClassReader of(byte[] binaryRepresentation) {
    if (EXPERIMENTAL) {
        ClassFileVersion classFileVersion = ClassFileVersion.ofClassFile(binaryRepresentation);
        if (classFileVersion.isGreaterThan(ClassFileVersion.JAVA_V14)) {
            binaryRepresentation[6] = (byte) (ClassFileVersion.JAVA_V14.getMajorVersion() >>> 8);
            binaryRepresentation[7] = (byte) ClassFileVersion.JAVA_V14.getMajorVersion();
            ClassReader classReader = new ClassReader(binaryRepresentation);
            binaryRepresentation[6] = (byte) (classFileVersion.getMajorVersion() >>> 8);
            binaryRepresentation[7] = (byte) classFileVersion.getMajorVersion();
            return classReader;
        } else {
            return new ClassReader(binaryRepresentation);
        }
    } else {
        return new ClassReader(binaryRepresentation);
    }
}
 
Example #6
Source File: MemberSubstitution.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) {
    typePool = typePoolResolver.resolve(instrumentedType, instrumentedMethod, typePool);
    return new SubstitutingMethodVisitor(methodVisitor,
            instrumentedType,
            instrumentedMethod,
            methodGraphCompiler,
            strict,
            replacementFactory.make(instrumentedType, instrumentedMethod, typePool),
            implementationContext,
            typePool,
            implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V11));
}
 
Example #7
Source File: FieldConstantTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstantCreationLegacy() throws Exception {
    when(classFileVersion.isAtLeast(ClassFileVersion.JAVA_V5)).thenReturn(false);
    when(declaringType.isVisibleTo(instrumentedType)).thenReturn(true);
    StackManipulation stackManipulation = new FieldConstant(fieldDescription);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(1));
    assertThat(size.getMaximalSize(), is(2));
    verify(methodVisitor).visitLdcInsn(BAZ);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKESTATIC,
            Type.getInternalName(Class.class),
            "forName",
            Type.getMethodDescriptor(Type.getType(Class.class), Type.getType(String.class)),
            false);
    verify(methodVisitor).visitLdcInsn(BAR);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKEVIRTUAL,
            "java/lang/Class",
            "getDeclaredField",
            "(Ljava/lang/String;)Ljava/lang/reflect/Field;",
            false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #8
Source File: AnnotationAppenderDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
private Class<?> makeTypeWithAnnotation(Annotation annotation) throws Exception {
    when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS);
    classWriter.visit(ClassFileVersion.ofThisVm().getMinorMajorVersion(),
            Opcodes.ACC_PUBLIC,
            BAR.replace('.', '/'),
            null,
            Type.getInternalName(Object.class),
            null);
    AnnotationVisitor annotationVisitor = classWriter.visitAnnotation(Type.getDescriptor(annotation.annotationType()), true);
    when(target.visit(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    AnnotationDescription annotationDescription = AnnotationDescription.ForLoadedAnnotation.of(annotation);
    annotationAppender.append(annotationDescription, valueFilter);
    classWriter.visitEnd();
    Class<?> bar = new ByteArrayClassLoader(getClass().getClassLoader(), Collections.singletonMap(BAR, classWriter.toByteArray())).loadClass(BAR);
    assertThat(bar.getName(), is(BAR));
    assertThat(bar.getSuperclass(), CoreMatchers.<Class<?>>is(Object.class));
    return bar;
}
 
Example #9
Source File: Implementation.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new default implementation context.
 *
 * @param instrumentedType            The description of the type that is currently subject of creation.
 * @param classFileVersion            The class file version of the created class.
 * @param auxiliaryTypeNamingStrategy The naming strategy for naming an auxiliary type.
 * @param typeInitializer             The type initializer of the created instrumented type.
 * @param auxiliaryClassFileVersion   The class file version to use for auxiliary classes.
 */
protected Default(TypeDescription instrumentedType,
                  ClassFileVersion classFileVersion,
                  AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy,
                  TypeInitializer typeInitializer,
                  ClassFileVersion auxiliaryClassFileVersion) {
    super(instrumentedType, classFileVersion);
    this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy;
    this.typeInitializer = typeInitializer;
    this.auxiliaryClassFileVersion = auxiliaryClassFileVersion;
    registeredAccessorMethods = new HashMap<SpecialMethodInvocation, DelegationRecord>();
    registeredGetters = new HashMap<FieldDescription, DelegationRecord>();
    registeredSetters = new HashMap<FieldDescription, DelegationRecord>();
    auxiliaryTypes = new HashMap<AuxiliaryType, DynamicType>();
    registeredFieldCacheEntries = new HashMap<FieldCacheEntry, FieldDescription.InDefinedShape>();
    registeredFieldCacheFields = new HashSet<FieldDescription.InDefinedShape>();
    suffix = RandomString.make();
    fieldCacheCanAppendEntries = true;
}
 
Example #10
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    StringBuilder stringBuilder = new StringBuilder("(");
    for (TypeDescription parameterType : parameterTypes) {
        stringBuilder.append(parameterType.getDescriptor());
    }
    String methodDescriptor = stringBuilder.append(')').append(returnType.getDescriptor()).toString();
    methodVisitor.visitInvokeDynamicInsn(methodName,
            methodDescriptor,
            new Handle(handle == legacyHandle || implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V11)
                    ? handle
                    : legacyHandle,
                    bootstrapMethod.getDeclaringType().getInternalName(),
                    bootstrapMethod.getInternalName(),
                    bootstrapMethod.getDescriptor(),
                    bootstrapMethod.getDeclaringType().isInterface()),
            arguments.toArray(new Object[0]));
    int stackSize = returnType.getStackSize().getSize() - StackSize.of(parameterTypes);
    return new Size(stackSize, Math.max(stackSize, 0));
}
 
Example #11
Source File: JavaVersionRule.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    Enforce enforce = method.getAnnotation(Enforce.class);
    if (enforce != null) {
        ClassFileVersion version;
        try {
            version = enforce.target() == void.class
                    ? currentVersion
                    : ClassFileVersion.of(enforce.target());
        } catch (IOException exception) {
            throw new AssertionError(exception);
        }
        if (j9 && !enforce.j9()) {
            return new OpenJ9Statement();
        } else if (enforce.value() != UNDEFINED && !version.isAtLeast(ClassFileVersion.ofJavaVersion(enforce.value()))) {
            return new NoOpStatement(enforce.value(), "at least", enforce.target());
        } else if (enforce.atMost() != UNDEFINED && !version.isAtMost(ClassFileVersion.ofJavaVersion(enforce.atMost()))) {
            return new NoOpStatement(enforce.atMost(), "at most", enforce.target());
        }
    }
    return base;
}
 
Example #12
Source File: AnnotationAppenderDefaultTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
private Class<?> makeTypeWithSuperClassAnnotation(Annotation annotation) throws Exception {
    when(valueFilter.isRelevant(any(AnnotationDescription.class), any(MethodDescription.InDefinedShape.class))).thenReturn(true);
    ClassWriter classWriter = new ClassWriter(AsmVisitorWrapper.NO_FLAGS);
    classWriter.visit(ClassFileVersion.ofThisVm().getMinorMajorVersion(),
            Opcodes.ACC_PUBLIC,
            BAR.replace('.', '/'),
            null,
            Type.getInternalName(Object.class),
            null);
    AnnotationVisitor annotationVisitor = classWriter.visitTypeAnnotation(TypeReference.newSuperTypeReference(-1).getValue(),
            null,
            Type.getDescriptor(annotation.annotationType()),
            true);
    when(target.visit(any(String.class), anyBoolean())).thenReturn(annotationVisitor);
    AnnotationDescription annotationDescription = AnnotationDescription.ForLoadedAnnotation.of(annotation);
    annotationAppender.append(annotationDescription, valueFilter);
    classWriter.visitEnd();
    Class<?> bar = new ByteArrayClassLoader(getClass().getClassLoader(), Collections.singletonMap(BAR, classWriter.toByteArray())).loadClass(BAR);
    assertThat(bar.getName(), is(BAR));
    assertThat(bar.getSuperclass(), CoreMatchers.<Class<?>>is(Object.class));
    return bar;
}
 
Example #13
Source File: RSocketRemoteServiceBuilder.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public T build() {
    CONSUMED_SERVICES.add(new ServiceLocator(group, service, version));
    RSocketRequesterRpcProxy proxy = getRequesterProxy();
    Class<T> dynamicType = (Class<T>) new ByteBuddy(ClassFileVersion.JAVA_V8)
            .subclass(serviceInterface)
            .name(serviceInterface.getSimpleName() + "RSocketStub")
            .method(ElementMatchers.not(ElementMatchers.isDefaultMethod()))
            .intercept(MethodDelegation.to(proxy))
            .make()
            .load(serviceInterface.getClassLoader())
            .getLoaded();
    try {
        return dynamicType.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #14
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 #15
Source File: FieldConstantTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstantCreationModernInvisible() throws Exception {
    when(classFileVersion.isAtLeast(ClassFileVersion.JAVA_V5)).thenReturn(true);
    when(declaringType.isVisibleTo(instrumentedType)).thenReturn(false);
    StackManipulation stackManipulation = new FieldConstant(fieldDescription);
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(1));
    assertThat(size.getMaximalSize(), is(2));
    verify(methodVisitor).visitLdcInsn(BAZ);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKESTATIC,
            Type.getInternalName(Class.class),
            "forName",
            Type.getMethodDescriptor(Type.getType(Class.class), Type.getType(String.class)),
            false);
    verify(methodVisitor).visitLdcInsn(BAR);
    verify(methodVisitor).visitMethodInsn(Opcodes.INVOKEVIRTUAL,
            "java/lang/Class",
            "getDeclaredField",
            "(Ljava/lang/String;)Ljava/lang/reflect/Field;",
            false);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #16
Source File: TrivialTypeTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testPlain() throws Exception {
    when(classFileVersion.getMinorMajorVersion()).thenReturn(ClassFileVersion.JAVA_V5.getMinorMajorVersion());
    DynamicType dynamicType = TrivialType.PLAIN.make(FOO, classFileVersion, methodAccessorFactory);
    assertThat(dynamicType.getTypeDescription().getName(), is(FOO));
    assertThat(dynamicType.getTypeDescription().getModifiers(), is(Opcodes.ACC_SYNTHETIC));
    assertThat(dynamicType.getTypeDescription().getDeclaredAnnotations().size(), is(0));
    assertThat(dynamicType.getAuxiliaryTypes().size(), is(0));
    assertThat(dynamicType.getLoadedTypeInitializers().get(dynamicType.getTypeDescription()).isAlive(), is(false));
}
 
Example #17
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimitiveTypeInLegacyConstantPoolRemapped() throws Exception {
    Class<?> dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V4)
            .with(TypeValidation.DISABLED)
            .subclass(Object.class)
            .defineMethod(FOO, Object.class, Visibility.PUBLIC)
            .intercept(FixedValue.value(int.class))
            .make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicType.getDeclaredMethod(FOO).invoke(dynamicType.getDeclaredConstructor().newInstance()), is((Object) int.class));
}
 
Example #18
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new decorating dynamic type builder.
 *
 * @param instrumentedType             The instrumented type to decorate.
 * @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 classFileLocator             The class file locator for locating the original type's class file.
 */
public DecoratingDynamicTypeBuilder(TypeDescription instrumentedType,
                                    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,
                                    ClassFileLocator classFileLocator) {
    this(instrumentedType,
            annotationRetention.isEnabled()
                    ? new TypeAttributeAppender.ForInstrumentedType.Differentiating(instrumentedType)
                    : TypeAttributeAppender.ForInstrumentedType.INSTANCE,
            AsmVisitorWrapper.NoOp.INSTANCE,
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            classWriterStrategy,
            ignoredMethods,
            Collections.<DynamicType>emptyList(),
            classFileLocator);
}
 
Example #19
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testAnnotationOnMethodPreJava5TypeAssertion() throws Exception {
    new ByteBuddy(ClassFileVersion.JAVA_V4)
            .subclass(Object.class)
            .defineMethod(FOO, void.class)
            .intercept(StubMethod.INSTANCE)
            .annotateMethod(AnnotationDescription.Builder.ofType(Foo.class).build())
            .make();
}
 
Example #20
Source File: AndroidClassLoadingStrategyTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testStubbedClassLoading() throws Exception {
    final DynamicType.Unloaded<?> dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V6)
            .subclass(Object.class)
            .method(named(TO_STRING)).intercept(FixedValue.value(FOO))
            .make();
    AndroidClassLoadingStrategy classLoadingStrategy = spy(new StubbedClassLoadingStrategy(folder, new StubbedClassLoaderDexCompilation()));
    doReturn(Collections.singletonMap(dynamicType.getTypeDescription(), Foo.class)).when(classLoadingStrategy).doLoad(eq(getClass().getClassLoader()),
            eq(Collections.singleton(dynamicType.getTypeDescription())),
            any(File.class));
    Map<TypeDescription, Class<?>> map = classLoadingStrategy.load(getClass().getClassLoader(), dynamicType.getAllTypes());
    assertThat(map.size(), is(1));
}
 
Example #21
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testStaticMethodOnInterfaceAssertion() throws Exception {
    new ByteBuddy(ClassFileVersion.JAVA_V6)
            .makeInterface()
            .defineMethod(FOO, String.class, Visibility.PUBLIC, Ownership.STATIC)
            .withoutCode()
            .make();
}
 
Example #22
Source File: SubclassDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new type builder for creating a subclass.
 *
 * @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 constructorStrategy          The constructor strategy to apply onto the instrumented type.
 */
public SubclassDynamicTypeBuilder(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,
                                  ConstructorStrategy constructorStrategy) {
    this(instrumentedType,
            new FieldRegistry.Default(),
            new MethodRegistry.Default(),
            new RecordComponentRegistry.Default(),
            TypeAttributeAppender.ForInstrumentedType.INSTANCE,
            AsmVisitorWrapper.NoOp.INSTANCE,
            classFileVersion,
            auxiliaryTypeNamingStrategy,
            annotationValueFilterFactory,
            annotationRetention,
            implementationContextFactory,
            methodGraphCompiler,
            typeValidation,
            visibilityBridgeStrategy,
            classWriterStrategy,
            ignoredMethods,
            Collections.<DynamicType>emptyList(),
            constructorStrategy);
}
 
Example #23
Source File: PluginEngineDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testOfEntryPoint() {
    EntryPoint entryPoint = mock(EntryPoint.class);
    ClassFileVersion classFileVersion = mock(ClassFileVersion.class);
    MethodNameTransformer methodNameTransformer = mock(MethodNameTransformer.class);
    ByteBuddy byteBuddy = mock(ByteBuddy.class);
    when(entryPoint.byteBuddy(classFileVersion)).thenReturn(byteBuddy);
    assertThat(Plugin.Engine.Default.of(entryPoint, classFileVersion, methodNameTransformer), hasPrototype(new Plugin.Engine.Default()
            .with(byteBuddy)
            .with(new Plugin.Engine.TypeStrategy.ForEntryPoint(entryPoint, methodNameTransformer))));
    verify(entryPoint).byteBuddy(classFileVersion);
    verifyNoMoreInteractions(entryPoint);
}
 
Example #24
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
    Label label = new Label();
    methodVisitor.visitJumpInsn(jumpCondition, label);
    methodVisitor.visitInsn(value);
    methodVisitor.visitInsn(Opcodes.IRETURN);
    methodVisitor.visitLabel(label);
    if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V6)) {
        methodVisitor.visitFrame(Opcodes.F_SAME, EMPTY.length, EMPTY, EMPTY.length, EMPTY);
    }
    return new Size(-1, 1);
}
 
Example #25
Source File: TypeProxy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public DynamicType make(String auxiliaryTypeName,
                        ClassFileVersion classFileVersion,
                        MethodAccessorFactory methodAccessorFactory) {
    return new ByteBuddy(classFileVersion)
            .with(TypeValidation.DISABLED)
            .ignore(ignoreFinalizer ? isFinalizer() : ElementMatchers.<MethodDescription>none())
            .subclass(proxiedType)
            .name(auxiliaryTypeName)
            .modifiers(DEFAULT_TYPE_MODIFIER)
            .implement(serializableProxy ? new Class<?>[]{Serializable.class} : new Class<?>[0])
            .method(any()).intercept(new MethodCall(methodAccessorFactory))
            .defineMethod(REFLECTION_METHOD, TargetType.class, Ownership.STATIC).intercept(SilentConstruction.INSTANCE)
            .make();
}
 
Example #26
Source File: CreatorOptimizer.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
protected byte[] generateOptimized(ClassName baseName, Constructor<?> ctor, Method factory) {
    final String tmpClassName = baseName.getSlashedTemplate();
    final DynamicType.Builder<?> builder =
            new ByteBuddy(ClassFileVersion.JAVA_V5)
                    .with(TypeValidation.DISABLED)
                    .subclass(OptimizedValueInstantiator.class) //default strategy ensures that all constructors are created
                    .name(tmpClassName)
                    .modifiers(Visibility.PUBLIC, TypeManifestation.FINAL)
                    .method(named("with"))
                    .intercept(
                            //call the constructor of this method that takes a single StdValueInstantiator arg
                            //the required arg is in the position 1 of the method's local variables
                            new Implementation.Simple(
                                    new ByteCodeAppender.Simple(
                                            new ConstructorCallStackManipulation.OfInstrumentedType.OneArg(
                                                    REFERENCE.loadFrom(1)
                                            ),
                                            MethodReturn.REFERENCE
                                    )
                            )

                    )
                    .method(named("createUsingDefault"))
                    .intercept(
                            new SimpleExceptionHandler(
                                    creatorInvokerStackManipulation(ctor, factory),
                                    creatorExceptionHandlerStackManipulation(),
                                    Exception.class,
                                    1 //we added a new local variable in the catch block
                            )
                    );


    return builder.make().getBytes();
}
 
Example #27
Source File: TypeWriterDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testPackagePrivateMethodOnInterfaceAssertionJava8() throws Exception {
    new ByteBuddy(ClassFileVersion.JAVA_V8)
            .makeInterface()
            .defineMethod(FOO, void.class)
            .withoutCode()
            .make();
}
 
Example #28
Source File: ClassConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V5) && typeDescription.isVisibleTo(implementationContext.getInstrumentedType())) {
        methodVisitor.visitLdcInsn(Type.getType(typeDescription.getDescriptor()));
    } else {
        methodVisitor.visitLdcInsn(typeDescription.getName());
        methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Class", "forName", "(Ljava/lang/String;)Ljava/lang/Class;", false);
    }
    return SIZE;
}
 
Example #29
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext) {
    methodVisitor.visitLabel(label);
    if (implementationContext.getClassFileVersion().isAtLeast(ClassFileVersion.JAVA_V6)) {
        methodVisitor.visitFrame(Opcodes.F_SAME1, EMPTY.length, EMPTY, INTEGER.length, INTEGER);
    }
    return new Size(0, 0);
}
 
Example #30
Source File: DecoratingDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}