Java Code Examples for net.bytebuddy.description.field.FieldDescription#InDefinedShape

The following examples show how to use net.bytebuddy.description.field.FieldDescription#InDefinedShape . 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: EqualsMethod.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeAppender appender(Target implementationTarget) {
    if (implementationTarget.getInstrumentedType().isInterface()) {
        throw new IllegalStateException("Cannot implement meaningful equals method for " + implementationTarget.getInstrumentedType());
    }
    List<FieldDescription.InDefinedShape> fields = new ArrayList<FieldDescription.InDefinedShape>(implementationTarget.getInstrumentedType()
            .getDeclaredFields()
            .filter(not(isStatic().or(ignored))));
    Collections.sort(fields, comparator);
    return new Appender(implementationTarget.getInstrumentedType(), new StackManipulation.Compound(
            superClassCheck.resolve(implementationTarget.getInstrumentedType()),
            MethodVariableAccess.loadThis(),
            MethodVariableAccess.REFERENCE.loadFrom(1),
            ConditionalReturn.onIdentity().returningTrue(),
            typeCompatibilityCheck.resolve(implementationTarget.getInstrumentedType())
    ), fields, nonNullable);
}
 
Example 2
Source File: ModifierAdjustment.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ModifierAdjustingClassVisitor wrap(TypeDescription instrumentedType,
                                          ClassVisitor classVisitor,
                                          Implementation.Context implementationContext,
                                          TypePool typePool,
                                          FieldList<FieldDescription.InDefinedShape> fields,
                                          MethodList<?> methods,
                                          int writerFlags,
                                          int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mappedFields = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mappedFields.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    Map<String, MethodDescription> mappedMethods = new HashMap<String, MethodDescription>();
    for (MethodDescription methodDescription : CompoundList.<MethodDescription>of(methods, new MethodDescription.Latent.TypeInitializer(instrumentedType))) {
        mappedMethods.put(methodDescription.getInternalName() + methodDescription.getDescriptor(), methodDescription);
    }
    return new ModifierAdjustingClassVisitor(classVisitor,
            typeAdjustments,
            fieldAdjustments,
            methodAdjustments,
            instrumentedType,
            mappedFields,
            mappedMethods);
}
 
Example 3
Source File: JavaConstant.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@code static}, {@code final} field constant.
 *
 * @param fieldDescription The field to represent a value of.
 * @return A dynamically resolved field value constant.
 */
public static Dynamic ofField(FieldDescription.InDefinedShape fieldDescription) {
    if (!fieldDescription.isStatic() || !fieldDescription.isFinal()) {
        throw new IllegalArgumentException("Field must be static and final: " + fieldDescription);
    }
    boolean selfDeclared = fieldDescription.getType().isPrimitive()
            ? fieldDescription.getType().asErasure().asBoxed().equals(fieldDescription.getType().asErasure())
            : fieldDescription.getDeclaringType().equals(fieldDescription.getType().asErasure());
    return new Dynamic(new ConstantDynamic(fieldDescription.getInternalName(),
            fieldDescription.getDescriptor(),
            new Handle(Opcodes.H_INVOKESTATIC,
                    CONSTANT_BOOTSTRAPS,
                    "getStaticFinal",
                    selfDeclared
                            ? "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;"
                            : "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/Class;Ljava/lang/Class;)Ljava/lang/Object;",
                    false), selfDeclared
            ? new Object[0]
            : new Object[]{Type.getType(fieldDescription.getDeclaringType().getDescriptor())}), fieldDescription.getType().asErasure());
}
 
Example 4
Source File: TransformerInvokerGenerator.java    From Diorite with MIT License 6 votes vote down vote up
@Override
        public ClassVisitor wrap(TypeDescription typeDescription, ClassVisitor cv, Context context, TypePool typePool,
                                 FieldList<FieldDescription.InDefinedShape> fieldList, MethodList<?> methodList, int i, int i1)
        {
//            public void visit(int version, int modifiers, String name, String signature, String superName, String[] interfaces) {
            cv.visit(ClassFileVersion.JAVA_V9.getMinorMajorVersion(), typeDescription.getModifiers(), typeDescription.getInternalName(), null,
                     typeDescription.getSuperClass().asErasure().getInternalName(), typeDescription.getInterfaces().asErasures().toInternalNames());
            TypeDescription clazz = this.clazz;
            String internalName = clazz.getInternalName();
            String descriptor = clazz.getDescriptor();
            MethodList<InDefinedShape> declaredMethods = clazz.getDeclaredMethods();
            int methodsSize = declaredMethods.size();
            String implName = GENERATED_PREFIX + "." + clazz.getName();
            String internalImplName = GENERATED_PREFIX.replace('.', '/') + "/" + internalName;
            String descriptorImplName = "L" + GENERATED_PREFIX.replace('.', '/') + "/" + internalName + ";";

            FieldVisitor fv;
            MethodVisitor mv;
            AnnotationVisitor av0;

            cv.visitEnd();
            return cv;
        }
 
Example 5
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new replacement that triggers a substitution based on a row of matchers.
 *
 * @param fieldMatcher        The field matcher to consider when discovering fields.
 * @param methodMatcher       The method matcher to consider when discovering methods.
 * @param matchFieldRead      {@code true} if field reading access should be matched.
 * @param matchFieldWrite     {@code true} if field writing access should be matched.
 * @param includeVirtualCalls {@code true} if virtual method calls should be matched.
 * @param includeSuperCalls   {@code true} if super method calls should be matched.
 * @param substitutionFactory The substitution factory to create a substitution from.
 */
protected Factory(ElementMatcher<? super FieldDescription.InDefinedShape> fieldMatcher,
                  ElementMatcher<? super MethodDescription> methodMatcher,
                  boolean matchFieldRead,
                  boolean matchFieldWrite,
                  boolean includeVirtualCalls,
                  boolean includeSuperCalls,
                  Substitution.Factory substitutionFactory) {
    this.fieldMatcher = fieldMatcher;
    this.methodMatcher = methodMatcher;
    this.matchFieldRead = matchFieldRead;
    this.matchFieldWrite = matchFieldWrite;
    this.includeVirtualCalls = includeVirtualCalls;
    this.includeSuperCalls = includeSuperCalls;
    this.substitutionFactory = substitutionFactory;
}
 
Example 6
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithFieldOfInstrumentedType() throws Exception {
    InstrumentedType instrumentedType = makePlainInstrumentedType();
    assertThat(instrumentedType.getDeclaredFields().size(), is(0));
    instrumentedType = instrumentedType.withField(new FieldDescription.Token(BAR, Opcodes.ACC_PUBLIC, TargetType.DESCRIPTION.asGenericType()));
    assertThat(instrumentedType.getDeclaredFields().size(), is(1));
    FieldDescription.InDefinedShape fieldDescription = instrumentedType.getDeclaredFields().get(0);
    assertThat(fieldDescription.getType().asErasure(), sameInstance((TypeDescription) instrumentedType));
    assertThat(fieldDescription.getModifiers(), is(Opcodes.ACC_PUBLIC));
    assertThat(fieldDescription.getName(), is(BAR));
    assertThat(fieldDescription.getDeclaringType(), sameInstance((TypeDescription) instrumentedType));
}
 
Example 7
Source File: EqualsMethodOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testEnumerationTypeComparatorRightEnumeration() {
    Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_ENUMERATION_TYPES;
    FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
    TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
    when(left.getType()).thenReturn(leftType);
    when(right.getType()).thenReturn(rightType);
    when(rightType.isEnum()).thenReturn(true);
    assertThat(comparator.compare(left, right), is(1));
}
 
Example 8
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new appender for implementing a hash code method.
 *
 * @param initialValue      Loads the initial hash code onto the operand stack.
 * @param multiplier        A multiplier for each value before adding a field's hash code value.
 * @param fieldDescriptions A list of fields to include in the hash code computation.
 * @param nonNullable       A matcher to determine fields of a reference type that cannot be {@code null}.
 */
protected Appender(StackManipulation initialValue,
                   int multiplier,
                   List<FieldDescription.InDefinedShape> fieldDescriptions,
                   ElementMatcher<? super FieldDescription.InDefinedShape> nonNullable) {
    this.initialValue = initialValue;
    this.multiplier = multiplier;
    this.fieldDescriptions = fieldDescriptions;
    this.nonNullable = nonNullable;
}
 
Example 9
Source File: MemberAttributeExtension.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public FieldVisitor wrap(TypeDescription instrumentedType, FieldDescription.InDefinedShape fieldDescription, FieldVisitor fieldVisitor) {
    return new FieldAttributeVisitor(fieldVisitor,
            fieldDescription,
            attributeAppenderFactory.make(instrumentedType),
            annotationValueFilterFactory.on(fieldDescription));
}
 
Example 10
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    return classVisitor;
}
 
Example 11
Source File: EqualsMethodOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimitiveTypeComparatorLeftPrimitive() {
    Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_TYPES;
    FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
    TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
    when(left.getType()).thenReturn(leftType);
    when(right.getType()).thenReturn(rightType);
    when(leftType.isPrimitive()).thenReturn(true);
    assertThat(comparator.compare(left, right), is(-1));
}
 
Example 12
Source File: EqualsMethodOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringTypeComparatorBothString() {
    Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_STRING_TYPES;
    FieldDescription.InDefinedShape left = mock(FieldDescription.InDefinedShape.class), right = mock(FieldDescription.InDefinedShape.class);
    TypeDescription.Generic leftType = mock(TypeDescription.Generic.class), rightType = mock(TypeDescription.Generic.class);
    when(left.getType()).thenReturn(leftType);
    when(right.getType()).thenReturn(rightType);
    when(leftType.represents(String.class)).thenReturn(true);
    when(rightType.represents(String.class)).thenReturn(true);
    assertThat(comparator.compare(left, right), is(0));
}
 
Example 13
Source File: BridgeClassVisitorWrapper.java    From kanela with Apache License 2.0 5 votes vote down vote up
@Override
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {

    return  BridgeClassVisitor.from(bridge, instrumentedType.getInternalName(), classVisitor);
}
 
Example 14
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ClassVisitor wrap(TypeDescription instrumentedType,
                         ClassVisitor classVisitor,
                         Implementation.Context implementationContext,
                         TypePool typePool,
                         FieldList<FieldDescription.InDefinedShape> fields,
                         MethodList<?> methods,
                         int writerFlags,
                         int readerFlags) {
    Map<String, FieldDescription.InDefinedShape> mapped = new HashMap<String, FieldDescription.InDefinedShape>();
    for (FieldDescription.InDefinedShape fieldDescription : fields) {
        mapped.put(fieldDescription.getInternalName() + fieldDescription.getDescriptor(), fieldDescription);
    }
    return new DispatchingVisitor(classVisitor, instrumentedType, mapped);
}
 
Example 15
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
@Override
public void visitFieldInsn(int opcode, String owner, String internalName, String descriptor) {
    TypePool.Resolution resolution = typePool.describe(owner.replace('/', '.'));
    if (resolution.isResolved()) {
        FieldList<FieldDescription.InDefinedShape> candidates = resolution.resolve().getDeclaredFields().filter(strict
                ? ElementMatchers.<FieldDescription>named(internalName).and(hasDescriptor(descriptor))
                : ElementMatchers.<FieldDescription>failSafe(named(internalName).and(hasDescriptor(descriptor))));
        if (!candidates.isEmpty()) {
            Replacement.Binding binding = replacement.bind(instrumentedType,
                    instrumentedMethod,
                    candidates.getOnly(),
                    opcode == Opcodes.PUTFIELD || opcode == Opcodes.PUTSTATIC);
            if (binding.isBound()) {
                TypeList.Generic parameters;
                TypeDescription.Generic result;
                switch (opcode) {
                    case Opcodes.PUTFIELD:
                        parameters = new TypeList.Generic.Explicit(candidates.getOnly().getDeclaringType(), candidates.getOnly().getType());
                        result = TypeDescription.Generic.VOID;
                        break;
                    case Opcodes.PUTSTATIC:
                        parameters = new TypeList.Generic.Explicit(candidates.getOnly().getType());
                        result = TypeDescription.Generic.VOID;
                        break;
                    case Opcodes.GETFIELD:
                        parameters = new TypeList.Generic.Explicit(candidates.getOnly().getDeclaringType());
                        result = candidates.getOnly().getType();
                        break;
                    case Opcodes.GETSTATIC:
                        parameters = new TypeList.Generic.Empty();
                        result = candidates.getOnly().getType();
                        break;
                    default:
                        throw new IllegalStateException("Unexpected opcode: " + opcode);
                }
                stackSizeBuffer = Math.max(stackSizeBuffer, binding.make(parameters, result, getFreeOffset())
                        .apply(new LocalVariableTracingMethodVisitor(mv), implementationContext)
                        .getMaximalSize() - result.getStackSize().getSize());
                return;
            }
        } else if (strict) {
            throw new IllegalStateException("Could not resolve " + owner.replace('/', '.')
                    + "." + internalName + descriptor + " using " + typePool);
        }
    } else if (strict) {
        throw new IllegalStateException("Could not resolve " + owner.replace('/', '.') + " using " + typePool);
    }
    super.visitFieldInsn(opcode, owner, internalName, descriptor);
}
 
Example 16
Source File: HashCodeMethod.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a new version of this hash code method implementation that ignores the specified fields additionally to any
 * previously specified fields.
 *
 * @param ignored A matcher to specify any fields that should be ignored.
 * @return A new version of this hash code method implementation that also ignores any fields matched by the provided matcher.
 */
public HashCodeMethod withIgnoredFields(ElementMatcher<? super FieldDescription.InDefinedShape> ignored) {
    return new HashCodeMethod(offsetProvider, multiplier, this.ignored.<FieldDescription.InDefinedShape>or(ignored), nonNullable);
}
 
Example 17
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Wraps a field visitor.
 *
 * @param instrumentedType The instrumented type.
 * @param fieldDescription The field that is currently being defined.
 * @param fieldVisitor     The original field visitor that defines the given field.
 * @return The wrapped field visitor.
 */
FieldVisitor wrap(TypeDescription instrumentedType, FieldDescription.InDefinedShape fieldDescription, FieldVisitor fieldVisitor);
 
Example 18
Source File: ElementMatchers.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Matches a field in its defined shape.
 *
 * @param matcher The matcher to apply to the matched field's defined shape.
 * @param <T>     The matched object's type.
 * @return A matcher that matches a matched field's defined shape.
 */
public static <T extends FieldDescription> ElementMatcher.Junction<T> definedField(ElementMatcher<? super FieldDescription.InDefinedShape> matcher) {
    return new DefinedShapeMatcher<T, FieldDescription.InDefinedShape>(matcher);
}
 
Example 19
Source File: AsmVisitorWrapper.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Defines a new field visitor wrapper to be applied if the given field matcher is matched. Previously defined
 * entries are applied before the given matcher is applied.
 *
 * @param matcher             The matcher to identify fields to be wrapped.
 * @param fieldVisitorWrapper The field visitor wrapper to be applied if the given matcher is matched.
 * @return A new ASM visitor wrapper that applied the given field visitor wrapper if the supplied matcher is matched.
 */
public ForDeclaredFields field(ElementMatcher<? super FieldDescription.InDefinedShape> matcher, FieldVisitorWrapper... fieldVisitorWrapper) {
    return field(matcher, Arrays.asList(fieldVisitorWrapper));
}
 
Example 20
Source File: MemberRemoval.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Specifies that any field that matches the specified matcher should be removed.
 *
 * @param matcher The matcher that decides upon field removal.
 * @return A new member removal instance that removes all previously specified members and any fields that match the specified matcher.
 */
public MemberRemoval stripFields(ElementMatcher<? super FieldDescription.InDefinedShape> matcher) {
    return new MemberRemoval(fieldMatcher.or(matcher), methodMatcher);
}