net.bytebuddy.implementation.bytecode.assign.TypeCasting Java Examples

The following examples show how to use net.bytebuddy.implementation.bytecode.assign.TypeCasting. 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: PropertyMutatorCollector.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 boolean mustCast = (beanValueAccess == MethodVariableAccess.REFERENCE);

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();
    operations.add(loadLocalVar()); // load local for cast bean
    operations.add(loadBeanValueArg());

    final AnnotatedMember member = prop.getMember();
    if (mustCast) {
        operations.add(TypeCasting.to(new ForLoadedType(getClassToCastBeanValueTo(member))));
    }

    operations.add(invocationOperation(member, beanClassDescription));
    operations.add(MethodReturn.VOID);

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #2
Source File: MethodConstant.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    TypeDescription auxiliaryType = implementationContext.register(PrivilegedMemberLookupAction.of(methodDescription));
    return new Compound(
            TypeCreation.of(auxiliaryType),
            Duplication.SINGLE,
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName,
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(auxiliaryType.getDeclaredMethods().filter(isConstructor()).getOnly()),
            MethodInvocation.invoke(DO_PRIVILEGED),
            TypeCasting.to(TypeDescription.ForLoadedType.of(methodDescription.isConstructor()
                    ? Constructor.class
                    : Method.class))
    ).apply(methodVisitor, implementationContext);
}
 
Example #3
Source File: DoParse.java    From curiostack with MIT License 5 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a field. This will be all the
 * elements for a repeated field.
 *
 * @param info description of the field to set.
 * @param beforeReadField jump target for before reading a field, used once this field is
 *     completed being set.
 * @param locals the method local variables
 * @param fieldsByName the instance fields
 */
private StackManipulation setFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  if (info.isMapField()) {
    return setMapFieldValue(info, beforeReadField, locals, fieldsByName);
  } else {
    final StackManipulation setConcreteValue = invoke(info.setValueMethod());
    final StackManipulation setSingleValue;
    if (info.valueJavaType() == JavaType.MESSAGE) {
      setSingleValue =
          new StackManipulation.Compound(
              TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
    } else if (info.valueType() == Type.ENUM && !info.isRepeated()) {
      // For non-repeated enums, we treat unknown as the default value.
      setSingleValue =
          new StackManipulation.Compound(ParseSupport_mapUnknownEnumValue, setConcreteValue);
    } else {
      setSingleValue = setConcreteValue;
    }
    if (info.descriptor().isRepeated()) {
      return setRepeatedFieldValue(info, beforeReadField, locals, fieldsByName, setSingleValue);
    } else {
      // Set a singular value, e.g.,
      // builder.setFoo(readValue());
      return new StackManipulation.Compound(
          locals.load(LocalVariable.builder),
          locals.load(LocalVariable.parser),
          readValue(info, fieldsByName, locals),
          setSingleValue,
          Removal.SINGLE,
          new Goto(beforeReadField));
    }
  }
}
 
Example #4
Source File: FieldAccessOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericFieldAccessGetter() throws Exception {
    TypeDescription genericErasure = mock(TypeDescription.class), declaredErasure = mock(TypeDescription.class);
    when(genericErasure.asErasure()).thenReturn(genericErasure);
    when(genericType.asErasure()).thenReturn(genericErasure);
    when(declaredType.asErasure()).thenReturn(declaredErasure);
    StackManipulation stackManipulation = FieldAccess.forField(genericField).read();
    assertThat(stackManipulation.isValid(), is(true));
    assertThat(stackManipulation, hasPrototype((StackManipulation) new StackManipulation.Compound(FieldAccess.forField(fieldDescription).read(), TypeCasting.to(genericErasure))));
}
 
Example #5
Source File: MethodInvocationGenericTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericMethodSpecial() throws Exception {
    TypeDescription genericErasure = mock(TypeDescription.class);
    when(methodReturnType.asErasure()).thenReturn(genericErasure);
    when(genericErasure.asErasure()).thenReturn(genericErasure);
    StackManipulation stackManipulation = MethodInvocation.invoke(methodDescription).special(targetType);
    assertThat(stackManipulation.isValid(), is(true));
    assertThat(stackManipulation, hasPrototype((StackManipulation) new StackManipulation.Compound(MethodInvocation.invoke(declaredMethod).special(targetType),
            TypeCasting.to(genericErasure))));
}
 
Example #6
Source File: MethodInvocationGenericTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericMethodVirtual() throws Exception {
    TypeDescription genericErasure = mock(TypeDescription.class);
    when(methodReturnType.asErasure()).thenReturn(genericErasure);
    when(genericErasure.asErasure()).thenReturn(genericErasure);
    StackManipulation stackManipulation = MethodInvocation.invoke(methodDescription).virtual(targetType);
    assertThat(stackManipulation.isValid(), is(true));
    assertThat(stackManipulation, hasPrototype((StackManipulation) new StackManipulation.Compound(MethodInvocation.invoke(declaredMethod).virtual(targetType),
            TypeCasting.to(genericErasure))));
}
 
Example #7
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, MethodDescription instrumentedMethod) {
    if (instrumentedMethod.isStatic()) {
        throw new IllegalStateException("Hash code method must not be static: " + instrumentedMethod);
    } else if (instrumentedMethod.getParameters().size() != 1 || instrumentedMethod.getParameters().getOnly().getType().isPrimitive()) {
        throw new IllegalStateException();
    } else if (!instrumentedMethod.getReturnType().represents(boolean.class)) {
        throw new IllegalStateException("Hash code method does not return primitive boolean: " + instrumentedMethod);
    }
    List<StackManipulation> stackManipulations = new ArrayList<StackManipulation>(3 + fieldDescriptions.size() * 8);
    stackManipulations.add(baseline);
    int padding = 0;
    for (FieldDescription.InDefinedShape fieldDescription : fieldDescriptions) {
        stackManipulations.add(MethodVariableAccess.loadThis());
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        stackManipulations.add(MethodVariableAccess.REFERENCE.loadFrom(1));
        stackManipulations.add(TypeCasting.to(instrumentedType));
        stackManipulations.add(FieldAccess.forField(fieldDescription).read());
        NullValueGuard nullValueGuard = fieldDescription.getType().isPrimitive() || fieldDescription.getType().isArray() || nonNullable.matches(fieldDescription)
                ? NullValueGuard.NoOp.INSTANCE
                : new NullValueGuard.UsingJump(instrumentedMethod);
        stackManipulations.add(nullValueGuard.before());
        stackManipulations.add(ValueComparator.of(fieldDescription.getType()));
        stackManipulations.add(nullValueGuard.after());
        padding = Math.max(padding, nullValueGuard.getRequiredVariablePadding());
    }
    stackManipulations.add(IntegerConstant.forValue(true));
    stackManipulations.add(MethodReturn.INTEGER);
    return new Size(new StackManipulation.Compound(stackManipulations).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize() + padding);
}
 
Example #8
Source File: MethodVariableAccess.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation ofIndex(TypeDescription parameterType, int index) {
    TypeDescription targetType = bridgeTarget.getParameters().get(index).getType().asErasure();
    return parameterType.equals(targetType)
            ? Trivial.INSTANCE
            : TypeCasting.to(targetType);
}
 
Example #9
Source File: ByteBuddy.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) {
    FieldDescription valuesField = instrumentedType.getDeclaredFields().filter(named(ENUM_VALUES)).getOnly();
    MethodDescription cloneMethod = TypeDescription.Generic.OBJECT.getDeclaredMethods().filter(named(CLONE_METHOD_NAME)).getOnly();
    return new Size(new StackManipulation.Compound(
            FieldAccess.forField(valuesField).read(),
            MethodInvocation.invoke(cloneMethod).virtual(valuesField.getType().asErasure()),
            TypeCasting.to(valuesField.getType().asErasure()),
            MethodReturn.REFERENCE
    ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize());
}
 
Example #10
Source File: AbstractCreateLocalVarStackManipulation.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public Size apply(MethodVisitor methodVisitor,
                  Implementation.Context implementationContext) {

    final List<StackManipulation> operations = new ArrayList<StackManipulation>();

    operations.add(MethodVariableAccess.REFERENCE.loadFrom(beanArgIndex())); //load the bean
    operations.add(TypeCasting.to(beanClassDescription));

    operations.add(MethodVariableAccess.REFERENCE.storeAt(localVarIndexCalculator.calculate()));

    final StackManipulation.Compound compound = new StackManipulation.Compound(operations);
    return compound.apply(methodVisitor, implementationContext);
}
 
Example #11
Source File: DoWrite.java    From curiostack with MIT License 5 votes vote down vote up
private static StackManipulation unbox(ProtoFieldInfo field) {
  switch (field.valueJavaType()) {
    case INT:
    case ENUM:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Integer.class)), PrimitiveUnboxingDelegate.INTEGER);
    case LONG:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Long.class)), PrimitiveUnboxingDelegate.LONG);
    case BOOLEAN:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Boolean.class)), PrimitiveUnboxingDelegate.BOOLEAN);
    case FLOAT:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Float.class)), PrimitiveUnboxingDelegate.FLOAT);
    case DOUBLE:
      return new StackManipulation.Compound(
          TypeCasting.to(new ForLoadedType(Double.class)), PrimitiveUnboxingDelegate.DOUBLE);
    case STRING:
      return TypeCasting.to(new ForLoadedType(String.class));
    case BYTE_STRING:
      return TypeCasting.to(new ForLoadedType(ByteString.class));
    case MESSAGE:
      return TypeCasting.to(new ForLoadedType(Message.class));
    default:
      throw new IllegalStateException("Unknown field type.");
  }
}
 
Example #12
Source File: FieldAccess.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation read() {
    return new StackManipulation.Compound(defined.read(), TypeCasting.to(targetType));
}
 
Example #13
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation virtual(TypeDescription invocationTarget) {
    return new StackManipulation.Compound(invocation.virtual(invocationTarget), TypeCasting.to(targetType));
}
 
Example #14
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation special(TypeDescription invocationTarget) {
    return new StackManipulation.Compound(invocation.special(invocationTarget), TypeCasting.to(targetType));
}
 
Example #15
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public StackManipulation onHandle(HandleType type) {
    return new Compound(invocation.onHandle(type), TypeCasting.to(targetType));
}
 
Example #16
Source File: MethodInvocation.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    return new Compound(invocation, TypeCasting.to(targetType)).apply(methodVisitor, implementationContext);
}
 
Example #17
Source File: DoParse.java    From curiostack with MIT License 4 votes vote down vote up
/**
 * Returns the {@link StackManipulation} for setting the value of a map field.
 *
 * <p>Roughly equivalent to:
 *
 * <pre>{@code
 * ParseSupport.parseObjectStart(parser);
 * while (!ParseSupport.checkObjectEnd(parser.currentToken())) {
 *   builder.putFoo(readKey(), readValue());
 * }
 * }</pre>
 */
private StackManipulation setMapFieldValue(
    ProtoFieldInfo info,
    Label beforeReadField,
    LocalVariables<LocalVariable> locals,
    Map<String, FieldDescription> fieldsByName) {
  final StackManipulation setConcreteValue = invoke(info.setValueMethod());
  final StackManipulation setMapEntry;
  if (info.valueJavaType() == JavaType.MESSAGE) {
    setMapEntry =
        new StackManipulation.Compound(
            TypeCasting.to(new ForLoadedType(info.javaClass())), setConcreteValue);
  } else {
    setMapEntry = setConcreteValue;
  }
  Label mapStart = new Label();
  Label afterSet = new Label();

  StackManipulation.Compound beforeReadKey =
      new StackManipulation.Compound(
          locals.load(LocalVariable.parser),
          ParseSupport_parseObjectStart,
          new SetJumpTargetLabel(mapStart),
          locals.load(LocalVariable.parser),
          Parser_currentToken,
          ParseSupport_checkObjectEnd,
          new IfTrue(beforeReadField));

  StackManipulation.Compound setValueAndPrepareForNext =
      new StackManipulation.Compound(
          setMapEntry,
          Removal.SINGLE,
          new SetJumpTargetLabel(afterSet),
          locals.load(LocalVariable.parser),
          Parser_nextToken,
          Removal.SINGLE,
          new Goto(mapStart));

  if (info.valueType() == Type.ENUM) {
    // We special-case enum since we may need to skip unknown values.
    final LocalVariable keyVar;
    switch (info.mapKeyField().valueJavaType()) {
      case INT:
        keyVar = LocalVariable.intMapKey;
        break;
      case LONG:
        keyVar = LocalVariable.longMapKey;
        break;
      case BOOLEAN:
        keyVar = LocalVariable.boolMapKey;
        break;
      case STRING:
        keyVar = LocalVariable.stringMapKey;
        break;
      default:
        throw new IllegalArgumentException("Invalid map key type");
    }

    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.store(keyVar),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        locals.store(LocalVariable.intvalue),
        locals.load(LocalVariable.intvalue),
        IntegerConstant.forValue(-1),
        new IfEqual(int.class, afterSet),
        locals.load(LocalVariable.builder),
        locals.load(keyVar),
        locals.load(LocalVariable.intvalue),
        setValueAndPrepareForNext);
  } else {
    return new StackManipulation.Compound(
        beforeReadKey,
        locals.load(LocalVariable.builder),
        locals.load(LocalVariable.parser),
        readValue(info.mapKeyField(), fieldsByName, locals),
        locals.load(LocalVariable.parser),
        Parser_nextToken,
        Removal.SINGLE,
        locals.load(LocalVariable.parser),
        readValue(info, fieldsByName, locals),
        setValueAndPrepareForNext);
  }
}