net.bytebuddy.implementation.bytecode.constant.TextConstant Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.constant.TextConstant. 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: GenerateIllegalPropertyCountExceptionStackManipulation.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    final MethodDescription.InDefinedShape messageConstructor =
            new ForLoadedType(IllegalArgumentException.class)
                    .getDeclaredMethods()
                    .filter(isConstructor())
                    .filter(takesArguments(1))
                    .filter(takesArgument(0, String.class))
                    .getOnly();

    final StackManipulation.Compound delegate = new StackManipulation.Compound(
            new ConstructorCallStackManipulation.KnownInDefinedShapeOfExistingType(
                    messageConstructor,
                    new TextConstant("Invalid field index (valid; 0 <= n < "+propertyCount+"): ")
            ),
            Throw.INSTANCE
    );

    return delegate.apply(methodVisitor, implementationContext);
}
 
Example #2
Source File: RedefinitionDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testDefaultInterfaceSubInterface() throws Exception {
    Class<?> interfaceType = Class.forName(DEFAULT_METHOD_INTERFACE);
    Class<?> dynamicInterfaceType = new ByteBuddy()
            .redefine(interfaceType)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(BAR), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    Class<?> dynamicClassType = new ByteBuddy()
            .subclass(dynamicInterfaceType)
            .make()
            .load(dynamicInterfaceType.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(dynamicClassType.getMethod(FOO).invoke(dynamicClassType.getDeclaredConstructor().newInstance()), is((Object) BAR));
    assertThat(dynamicInterfaceType.getDeclaredMethods().length, is(1));
    assertThat(dynamicClassType.getDeclaredMethods().length, is(0));
}
 
Example #3
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testExplicitTypeInitializer() throws Exception {
    assertThat(createPlain()
            .defineField(FOO, String.class, Ownership.STATIC, Visibility.PUBLIC)
            .initializer(new ByteCodeAppender() {
                public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
                    return new Size(new StackManipulation.Compound(
                            new TextConstant(FOO),
                            FieldAccess.forField(instrumentedMethod.getDeclaringType().getDeclaredFields().filter(named(FOO)).getOnly()).write()
                    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
                }
            }).make()
            .load(ClassLoadingStrategy.BOOTSTRAP_LOADER, ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredField(FOO)
            .get(null), is((Object) FOO));
}
 
Example #4
Source File: MethodDelegationChainedTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testChainingNonVoid() throws Exception {
    NonVoidInterceptor nonVoidInterceptor = new NonVoidInterceptor();

    DynamicType.Loaded<Foo> dynamicType = new ByteBuddy().subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(MethodDelegation.
                    withDefaultConfiguration()
                    .filter(isDeclaredBy(NonVoidInterceptor.class))
                    .to(nonVoidInterceptor)
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredConstructor().newInstance().foo(), is(FOO));
    assertThat(nonVoidInterceptor.intercepted, is(true));
}
 
Example #5
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testMethodInvocationUsingStackManipulation() throws Exception {
    DynamicType.Loaded<SimpleMethod> loaded = new ByteBuddy()
        .subclass(SimpleMethod.class)
        .method(named(FOO))
        .intercept(MethodCall.invoke(String.class.getMethod("toUpperCase")).on(new TextConstant(FOO), String.class))
        .make()
        .load(SimpleMethod.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    SimpleMethod instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.foo(), is(FOO.toUpperCase()));
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(SimpleMethod.class)));
    assertThat(instance, instanceOf(SimpleMethod.class));
}
 
Example #6
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithExplicitArgumentStackManipulation() throws Exception {
    DynamicType.Loaded<MethodCallWithExplicitArgument> loaded = new ByteBuddy()
            .subclass(MethodCallWithExplicitArgument.class)
            .method(isDeclaredBy(MethodCallWithExplicitArgument.class))
            .intercept(MethodCall.invokeSuper().with(new TextConstant(FOO), String.class))
            .make()
            .load(MethodCallWithExplicitArgument.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO, String.class), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallWithExplicitArgument instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallWithExplicitArgument.class)));
    assertThat(instance, instanceOf(MethodCallWithExplicitArgument.class));
    assertThat(instance.foo(BAR), is(FOO));
}
 
Example #7
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplementationAppendingMethod() throws Exception {
    DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy()
            .subclass(MethodCallAppending.class)
            .method(isDeclaredBy(MethodCallAppending.class))
            .intercept(MethodCall.invokeSuper().andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class)));
    assertThat(instance, instanceOf(MethodCallAppending.class));
    assertThat(instance.foo(), is((Object) FOO));
    instance.assertOnlyCall(FOO);
}
 
Example #8
Source File: MethodCallTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testImplementationAppendingConstructor() throws Exception {
    DynamicType.Loaded<MethodCallAppending> loaded = new ByteBuddy()
            .subclass(MethodCallAppending.class)
            .method(isDeclaredBy(MethodCallAppending.class))
            .intercept(MethodCall.construct(Object.class.getDeclaredConstructor())
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(MethodCallAppending.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(loaded.getLoadedAuxiliaryTypes().size(), is(0));
    assertThat(loaded.getLoaded().getDeclaredMethods().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredMethod(FOO), not(nullValue(Method.class)));
    assertThat(loaded.getLoaded().getDeclaredConstructors().length, is(1));
    assertThat(loaded.getLoaded().getDeclaredFields().length, is(0));
    MethodCallAppending instance = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(instance.getClass(), not(CoreMatchers.<Class<?>>is(MethodCallAppending.class)));
    assertThat(instance, instanceOf(MethodCallAppending.class));
    assertThat(instance.foo(), is((Object) FOO));
    instance.assertZeroCalls();
}
 
Example #9
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTransformationExistingMethod() throws Exception {
    Class<?> type = create(Transform.class)
            .method(named(FOO))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .transform(Transformer.ForMethod.withModifiers(MethodManifestation.FINAL))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method foo = type.getDeclaredMethod(FOO);
    assertThat(foo.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
    assertThat(foo.getModifiers(), is(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC));
}
 
Example #10
Source File: AbstractDynamicTypeBuilderForInliningTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBridgeMethodCreation() throws Exception {
    Class<?> dynamicType = create(BridgeRetention.Inner.class)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertEquals(String.class, dynamicType.getDeclaredMethod(FOO).getReturnType());
    assertThat(dynamicType.getDeclaredMethod(FOO).getGenericReturnType(), is((Type) String.class));
    BridgeRetention<String> bridgeRetention = (BridgeRetention<String>) dynamicType.getDeclaredConstructor().newInstance();
    assertThat(bridgeRetention.foo(), is(FOO));
    bridgeRetention.assertZeroCalls();
}
 
Example #11
Source File: SubclassDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testBridgeMethodCreation() throws Exception {
    Class<?> dynamicType = new ByteBuddy()
            .subclass(BridgeRetention.Inner.class)
            .method(named(FOO)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded();
    assertEquals(String.class, dynamicType.getDeclaredMethod(FOO).getReturnType());
    assertThat(dynamicType.getDeclaredMethod(FOO).getGenericReturnType(), is((Type) String.class));
    BridgeRetention<String> bridgeRetention = (BridgeRetention<String>) dynamicType.getDeclaredConstructor().newInstance();
    assertThat(bridgeRetention.foo(), is(FOO));
    bridgeRetention.assertZeroCalls();
}
 
Example #12
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoredMethodDoesNotApplyForDefined() throws Exception {
    Class<?> type = createPlain()
            .ignoreAlso(named(FOO))
            .defineMethod(FOO, String.class, Visibility.PUBLIC)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredMethod(FOO).invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #13
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoredMethod() throws Exception {
    Class<?> type = createPlain()
            .ignoreAlso(named(TO_STRING))
            .method(named(TO_STRING))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance().toString(), CoreMatchers.not(FOO));
}
 
Example #14
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTransformation() throws Exception {
    Class<?> type = createPlain()
            .method(named(TO_STRING))
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .transform(Transformer.ForMethod.withModifiers(MethodManifestation.FINAL))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(type.getDeclaredConstructor().newInstance().toString(), is(FOO));
    assertThat(type.getDeclaredMethod(TO_STRING).getModifiers(), is(Opcodes.ACC_FINAL | Opcodes.ACC_PUBLIC));
}
 
Example #15
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructorInvokingMethod() throws Exception {
    Class<?> type = createPlain()
            .defineMethod(FOO, Object.class, Visibility.PUBLIC)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method method = type.getDeclaredMethod(FOO);
    assertThat(method.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #16
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testApplicationOrder() throws Exception {
    assertThat(createPlain()
            .method(named(TO_STRING)).intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .method(named(TO_STRING)).intercept(new Implementation.Simple(new TextConstant(BAR), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .getDeclaredConstructor()
            .newInstance()
            .toString(), is(BAR));
}
 
Example #17
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodDefinition() throws Exception {
    Class<?> type = createPlain()
            .defineMethod(FOO, Object.class, Visibility.PUBLIC)
            .throwing(Exception.class)
            .intercept(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE))
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    Method method = type.getDeclaredMethod(FOO);
    assertThat(method.getReturnType(), CoreMatchers.<Class<?>>is(Object.class));
    assertThat(method.getExceptionTypes(), is(new Class<?>[]{Exception.class}));
    assertThat(method.getModifiers(), is(Modifier.PUBLIC));
    assertThat(method.invoke(type.getDeclaredConstructor().newInstance()), is((Object) FOO));
}
 
Example #18
Source File: SuperMethodCallOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAndThen() throws Exception {
    DynamicType.Loaded<Foo> loaded = new ByteBuddy()
            .subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(SuperMethodCall.INSTANCE.andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    Foo foo = loaded.getLoaded().getDeclaredConstructor().newInstance();
    assertThat(foo.foo(), is(FOO));
    foo.assertOnlyCall(FOO);
}
 
Example #19
Source File: MethodDelegationChainedTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testChainingVoid() throws Exception {
    VoidInterceptor voidInterceptor = new VoidInterceptor();
    DynamicType.Loaded<Foo> dynamicType = new ByteBuddy().subclass(Foo.class)
            .method(isDeclaredBy(Foo.class))
            .intercept(MethodDelegation.withDefaultConfiguration()
                    .filter(isDeclaredBy(VoidInterceptor.class))
                    .to(voidInterceptor)
                    .andThen(new Implementation.Simple(new TextConstant(FOO), MethodReturn.REFERENCE)))
            .make()
            .load(Foo.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER);
    assertThat(dynamicType.getLoaded().getDeclaredConstructor().newInstance().foo(), is(FOO));
    assertThat(voidInterceptor.intercepted, is(true));
}
 
Example #20
Source File: ByteBuddyTutorialExamplesTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
public MethodDelegationBinder.ParameterBinding<?> bind(AnnotationDescription.Loadable<StringValue> annotation,
                                                       MethodDescription source,
                                                       ParameterDescription target,
                                                       Implementation.Target implementationTarget,
                                                       Assigner assigner,
                                                       Assigner.Typing typing) {
    if (!target.getType().asErasure().represents(String.class)) {
        throw new IllegalStateException(target + " makes wrong use of StringValue");
    }
    StackManipulation constant = new TextConstant(annotation.load().value());
    return new MethodDelegationBinder.ParameterBinding.Anonymous(constant);
}
 
Example #21
Source File: NexusAccessor.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext, MethodDescription instrumentedMethod) {
    try {
        return new ByteCodeAppender.Simple(new StackManipulation.Compound(
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("getSystemClassLoader"))),
                new TextConstant(Nexus.class.getName()),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(ClassLoader.class.getMethod("loadClass", String.class))),
                new TextConstant("initialize"),
                ArrayFactory.forType(TypeDescription.Generic.CLASS)
                        .withValues(Arrays.asList(
                                ClassConstant.of(TypeDescription.CLASS),
                                ClassConstant.of(TypeDescription.ForLoadedType.of(int.class)))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Class.class.getMethod("getMethod", String.class, Class[].class))),
                NullConstant.INSTANCE,
                ArrayFactory.forType(TypeDescription.Generic.OBJECT)
                        .withValues(Arrays.asList(
                                ClassConstant.of(instrumentedMethod.getDeclaringType().asErasure()),
                                new StackManipulation.Compound(
                                        IntegerConstant.forValue(identification),
                                        MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Integer.class.getMethod("valueOf", int.class)))))),
                MethodInvocation.invoke(new MethodDescription.ForLoadedMethod(Method.class.getMethod("invoke", Object.class, Object[].class))),
                Removal.SINGLE
        )).apply(methodVisitor, implementationContext, instrumentedMethod);
    } catch (NoSuchMethodException exception) {
        throw new IllegalStateException("Cannot locate method", exception);
    }
}
 
Example #22
Source File: ExceptionMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation make() {
    return new StackManipulation.Compound(
            TypeCreation.of(throwableType),
            Duplication.SINGLE,
            new TextConstant(message),
            MethodInvocation.invoke(targetConstructor));
}
 
Example #23
Source File: ToStringMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("toString method must not be static: " + instrumentedMethod);
    } else if (!instrumentedMethod.getReturnType().asErasure().isAssignableFrom(String.class)) {
        throw new IllegalStateException("toString method does not return String-compatible type: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(Math.max(0, fieldDescriptions.size() * 7 - 2) + 10);
    stackManipulations.add(TypeCreation.of(TypeDescription.ForLoadedType.of(StringBuilder.class)));
    stackManipulations.add(Duplication.SINGLE);
    stackManipulations.add(new TextConstant(prefix));
    stackManipulations.add(MethodInvocation.invoke(STRING_BUILDER_CONSTRUCTOR));
    stackManipulations.add(new TextConstant(start));
    stackManipulations.add(ValueConsumer.STRING);
    boolean first = true;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        if (first) {
            first = false;
        } else {
            stackManipulations.add(new TextConstant(separator));
            stackManipulations.add(ValueConsumer.STRING);
        }
        stackManipulations.add(new TextConstant(fieldDescription.getName() + definer));
        stackManipulations.add(ValueConsumer.STRING);
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(ValueConsumer.of(fieldDescription.getType().asErasure()));
    }
    stackManipulations.add(new TextConstant(end));
    stackManipulations.add(ValueConsumer.STRING);
    stackManipulations.add(MethodInvocation.invoke(TO_STRING));
    stackManipulations.add(MethodReturn.REFERENCE);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #24
Source File: SetSerializedFieldName.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public Size apply(
    MethodVisitor methodVisitor,
    Context implementationContext,
    MethodDescription instrumentedMethod) {
  Map<String, FieldDescription> fieldsByName = CodeGenUtil.fieldsByName(implementationContext);
  StackManipulation.Size operandStackSize =
      new StackManipulation.Compound(
              new TextConstant(unserializedFieldValue),
              SerializeSupport_serializeString,
              FieldAccess.forField(fieldsByName.get(fieldName)).write())
          .apply(methodVisitor, implementationContext);
  return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #25
Source File: DoWrite.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Retrurns a {@link StackManipulation} that checks whether the value in the message is a default
 * value, and if so jumps to after serialization to skip the serialization of the default value.
 * e.g.,
 *
 * <pre>{code
 *   if (message.getFoo() != field.getDefaultValue) {
 *     ...
 *   }
 *   // afterSerializeField
 * }</pre>
 */
private static StackManipulation checkDefaultValue(
    ProtoFieldInfo info,
    LocalVariables<LocalVariable> locals,
    StackManipulation getValue,
    StackManipulation getDefaultInstance,
    Label afterSerializeField) {
  if (info.isInOneof()) {
    // For one-ofs, we can just check the set field number directly.
    return new StackManipulation.Compound(
        locals.load(LocalVariable.message),
        CodeGenUtil.invoke(info.oneOfCaseMethod()),
        EnumLite_getNumber,
        IntegerConstant.forValue(info.descriptor().getNumber()),
        new IfIntsNotEqual(afterSerializeField));
  } else if (!info.isRepeated()) {
    switch (info.valueJavaType()) {
      case INT:
        return checkPrimitiveDefault(
            getValue,
            IntegerConstant.forValue((int) info.descriptor().getDefaultValue()),
            int.class,
            afterSerializeField);
      case LONG:
        return checkPrimitiveDefault(
            getValue,
            LongConstant.forValue((long) info.descriptor().getDefaultValue()),
            long.class,
            afterSerializeField);
      case FLOAT:
        return checkPrimitiveDefault(
            getValue,
            FloatConstant.forValue((float) info.descriptor().getDefaultValue()),
            float.class,
            afterSerializeField);
      case DOUBLE:
        return checkPrimitiveDefault(
            getValue,
            DoubleConstant.forValue((double) info.descriptor().getDefaultValue()),
            double.class,
            afterSerializeField);
      case BOOLEAN:
        return checkPrimitiveDefault(
            getValue,
            IntegerConstant.forValue((boolean) info.descriptor().getDefaultValue()),
            boolean.class,
            afterSerializeField);
      case ENUM:
        return checkPrimitiveDefault(
            getValue,
            IntegerConstant.forValue(
                ((EnumValueDescriptor) info.descriptor().getDefaultValue()).getNumber()),
            int.class,
            afterSerializeField);
      case STRING:
        return new StackManipulation.Compound(
            getValue,
            new TextConstant((String) info.descriptor().getDefaultValue()),
            Object_equals,
            new IfEqual(Object.class, afterSerializeField));
      case BYTE_STRING:
        // We'll use the default instance to get the default value for types that can't be
        // loaded into the constant pool. Since it's a constant, the somewhat indirect reference
        // should get inlined and be the same as a class constant.
        return new StackManipulation.Compound(
            getValue,
            getDefaultInstance,
            invoke(info.getValueMethod()),
            Object_equals,
            new IfEqual(Object.class, afterSerializeField));
      case MESSAGE:
        return new StackManipulation.Compound(
            locals.load(LocalVariable.message),
            invoke(info.hasValueMethod()),
            new IfFalse(afterSerializeField));
      default:
        throw new IllegalStateException("Unknown JavaType: " + info.valueJavaType());
    }
  } else {
    return new StackManipulation.Compound(
        locals.load(LocalVariable.message),
        CodeGenUtil.invoke(info.repeatedValueCountMethod()),
        new IfFalse(afterSerializeField));
  }
}