net.bytebuddy.description.type.TypeDescription Java Examples

The following examples show how to use net.bytebuddy.description.type.TypeDescription. 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: FieldProxyBinderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetterForExplicitNamedFieldInNamedType() throws Exception {
    when(target.getType()).thenReturn(genericSetterType);
    doReturn(Foo.class).when(annotation).declaringType();
    when(instrumentedType.isAssignableTo(TypeDescription.ForLoadedType.of(Foo.class))).thenReturn(true);
    when(annotation.value()).thenReturn(FOO);
    when(fieldDescription.getActualName()).thenReturn(FOO);
    when(source.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    when(source.getParameters()).thenReturn(new ParameterList.Explicit.ForTypes(source, fieldType));
    when(source.getName()).thenReturn("setFoo");
    when(source.getInternalName()).thenReturn("setFoo");
    when(fieldDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    MethodDelegationBinder.ParameterBinding<?> binding = new FieldProxy.Binder(getterMethod, setterMethod).bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
    assertThat(binding.isValid(), is(true));
}
 
Example #2
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
@SuppressWarnings("unchecked")
public void testAnnotationTypeOnMethodExceptionType() throws Exception {
    Class<? extends Annotation> typeAnnotationType = (Class<? extends Annotation>) Class.forName(TYPE_VARIABLE_NAME);
    MethodDescription.InDefinedShape value = TypeDescription.ForLoadedType.of(typeAnnotationType).getDeclaredMethods().filter(named(VALUE)).getOnly();
    Method method = createPlain()
            .merge(TypeManifestation.ABSTRACT)
            .defineMethod(FOO, void.class).throwing(TypeDescription.Generic.Builder.rawType(Exception.class)
                    .build(AnnotationDescription.Builder.ofType(typeAnnotationType).define(VALUE, INTEGER_VALUE).build()))
            .withoutCode()
            .make()
            .load(typeAnnotationType.getClassLoader(), ClassLoadingStrategy.Default.CHILD_FIRST)
            .getLoaded()
            .getDeclaredMethod(FOO);
    assertThat(method.getExceptionTypes().length, is(1));
    assertThat(method.getExceptionTypes()[0], is((Object) Exception.class));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveExceptionType(method, 0).asList().size(), is(1));
    assertThat(TypeDescription.Generic.AnnotationReader.DISPATCHER.resolveExceptionType(method, 0).asList().ofType(typeAnnotationType)
            .getValue(value).resolve(Integer.class), is(INTEGER_VALUE));
}
 
Example #3
Source File: BiDirectionalAssociationHandler.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static String getMappedByManyToMany(FieldDescription target, TypeDescription targetEntity, ByteBuddyEnhancementContext context) {
	for ( FieldDescription f : targetEntity.getDeclaredFields() ) {
		if ( context.isPersistentField( f )
				&& target.getName().equals( getMappedByNotManyToMany( f ) )
				&& target.getDeclaringType().asErasure().isAssignableTo( entityType( f.getType() ) ) ) {
			log.debugf(
					"mappedBy association for field [%s#%s] is [%s#%s]",
					target.getDeclaringType().asErasure().getName(),
					target.getName(),
					targetEntity.getName(),
					f.getName()
			);
			return f.getName();
		}
	}
	return null;
}
 
Example #4
Source File: AsmVisitorWrapperNoOpTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrapperChain() throws Exception {
    ClassVisitor classVisitor = mock(ClassVisitor.class);
    assertThat(AsmVisitorWrapper.NoOp.INSTANCE.wrap(mock(TypeDescription.class),
            classVisitor,
            mock(Implementation.Context.class),
            mock(TypePool.class),
            new FieldList.Empty<FieldDescription.InDefinedShape>(),
            new MethodList.Empty<MethodDescription>(),
            IGNORED,
            IGNORED), is(classVisitor));
    verifyZeroInteractions(classVisitor);
}
 
Example #5
Source File: JavaTypeTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallSite() throws Exception {
    assertThat(JavaType.CALL_SITE.getTypeStub().getName(), is("java.lang.invoke.CallSite"));
    assertThat(JavaType.CALL_SITE.getTypeStub().getModifiers(), is(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT));
    assertThat(JavaType.CALL_SITE.getTypeStub().getSuperClass(), is(TypeDescription.Generic.OBJECT));
    assertThat(JavaType.CALL_SITE.getTypeStub().getInterfaces().size(), is(0));
}
 
Example #6
Source File: Controller.java    From Diorite with MIT License 5 votes vote down vote up
@Override
protected ControllerClassData addClassData(TypeDescription typeDescription,
                                           org.diorite.inject.impl.data.ClassData<TypeDescription.ForLoadedType.Generic> classData)
{
    if (! (classData instanceof ControllerClassData))
    {
        throw new IllegalArgumentException("Unsupported class data for this controller");
    }
    this.map.put(typeDescription, classData);
    Lock lock = this.lock.writeLock();
    try
    {
        lock.lock();
        ((ControllerClassData) classData).setIndex(this.dataList.size());
        this.dataList.add(classData);
    }
    finally
    {
        lock.unlock();
    }
    try
    {
        ByteBuddyAgent.getInstrumentation().retransformClasses(AsmUtils.toClass(typeDescription));
    }
    catch (Exception e)
    {
        throw new TransformerError(e);
    }
    return (ControllerClassData) classData;
}
 
Example #7
Source File: JavaConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Object asConstantPoolValue() {
    StringBuilder stringBuilder = new StringBuilder().append('(');
    for (TypeDescription parameterType : getParameterTypes()) {
        stringBuilder.append(parameterType.getDescriptor());
    }
    return Type.getMethodType(stringBuilder.append(')').append(getReturnType().getDescriptor()).toString());
}
 
Example #8
Source File: EqualsMethodOtherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrimitiveWrapperTypeComparatorLeftPrimitiveWrapper() {
    Comparator<FieldDescription.InDefinedShape> comparator = EqualsMethod.TypePropertyComparator.FOR_PRIMITIVE_WRAPPER_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);
    TypeDescription leftErasure = mock(TypeDescription.class), rightErasure = mock(TypeDescription.class);
    when(leftType.asErasure()).thenReturn(leftErasure);
    when(rightType.asErasure()).thenReturn(rightErasure);
    when(leftErasure.isPrimitiveWrapper()).thenReturn(true);
    assertThat(comparator.compare(left, right), is(-1));
}
 
Example #9
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Linked compile(TypeDefinition typeDefinition, TypeDescription viewPoint) {
    LinkedHashMap<MethodDescription.SignatureToken, Node> nodes = new LinkedHashMap<MethodDescription.SignatureToken, Node>();
    for (MethodDescription methodDescription : typeDefinition.getDeclaredMethods().filter(isVirtual().and(not(isBridge())).and(isVisibleTo(viewPoint)))) {
        nodes.put(methodDescription.asSignatureToken(), new Node.Simple(methodDescription));
    }
    return new Linked.Delegation(new MethodGraph.Simple(nodes), Empty.INSTANCE, Collections.<TypeDescription, MethodGraph>emptyMap());
}
 
Example #10
Source File: PipeBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testParameterBindingOnIllegalTargetTypeThrowsException() throws Exception {
    TypeDescription.Generic targetType = mock(TypeDescription.Generic.class);
    TypeDescription rawTargetType = mock(TypeDescription.class);
    when(targetType.asErasure()).thenReturn(rawTargetType);
    when(target.getType()).thenReturn(targetType);
    binder.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC);
}
 
Example #11
Source File: StubValueBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonVoidAssignableReturnType() throws Exception {
    when(target.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(source.getReturnType()).thenReturn(genericType);
    when(stackManipulation.isValid()).thenReturn(true);
    assertThat(StubValue.Binder.INSTANCE.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC).isValid(), is(true));
}
 
Example #12
Source File: InvokeDynamicTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
@JavaVersionRule.Enforce(7)
public void testBootstrapFieldNotExistent() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(Class.forName(BOOTSTRAP_CLASS));
    new ByteBuddy()
            .subclass(Simple.class)
            .method(isDeclaredBy(Simple.class))
            .intercept(InvokeDynamic.bootstrap(typeDescription.getDeclaredMethods().filter(named("bootstrapSimple")).getOnly())
                    .invoke(QUX, String.class)
                    .withField(FOO)
                    .withAssigner(Assigner.DEFAULT, Assigner.Typing.DYNAMIC))
            .make();
}
 
Example #13
Source File: TargetMethodAnnotationDrivenBinder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new delegation processor.
 *
 * @param parameterBinders A list of parameter binder delegates. Each such delegate is responsible for creating
 *                         a {@link net.bytebuddy.implementation.bind.MethodDelegationBinder.ParameterBinding}
 *                         for a specific annotation.
 * @return A corresponding delegation processor.
 */
protected static DelegationProcessor of(List<? extends ParameterBinder<?>> parameterBinders) {
    Map<TypeDescription, ParameterBinder<?>> parameterBinderMap = new HashMap<TypeDescription, ParameterBinder<?>>();
    for (ParameterBinder<?> parameterBinder : parameterBinders) {
        if (parameterBinderMap.put(TypeDescription.ForLoadedType.of(parameterBinder.getHandledType()), parameterBinder) != null) {
            throw new IllegalArgumentException("Attempt to bind two handlers to " + parameterBinder.getHandledType());
        }
    }
    return new DelegationProcessor(parameterBinderMap);
}
 
Example #14
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testHasSuperType() throws Exception {
    assertThat(ElementMatchers.hasSuperType(ElementMatchers.is(Object.class)).matches(TypeDescription.STRING), is(true));
    assertThat(ElementMatchers.hasSuperType(ElementMatchers.is(String.class)).matches(TypeDescription.OBJECT), is(false));
    assertThat(ElementMatchers.hasSuperType(ElementMatchers.is(Serializable.class)).matches(TypeDescription.STRING), is(true));
    assertThat(ElementMatchers.hasSuperType(ElementMatchers.is(Serializable.class)).matches(TypeDescription.OBJECT), is(false));
}
 
Example #15
Source File: SkyWalkingAgent.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public void onIgnored(final TypeDescription typeDescription,
                      final ClassLoader classLoader,
                      final JavaModule module,
                      final boolean loaded) {

}
 
Example #16
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 #17
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Replacement make(TypeDescription instrumentedType, MethodDescription instrumentedMethod, TypePool typePool) {
    return new ForElementMatchers(fieldMatcher,
            methodMatcher,
            matchFieldRead,
            matchFieldWrite,
            includeVirtualCalls,
            includeSuperCalls,
            substitutionFactory.make(instrumentedType, instrumentedMethod, typePool));
}
 
Example #18
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnyOfFieldDefinedShape() throws Exception {
    Field field = GenericFieldType.class.getDeclaredField(FOO);
    FieldDescription fieldDescription = TypeDescription.ForLoadedType.of(GenericFieldType.Inner.class).getSuperClass()
            .getDeclaredFields().filter(named(FOO)).getOnly();
    assertThat(ElementMatchers.anyOf(field).matches(fieldDescription), is(true));
    assertThat(ElementMatchers.definedField(ElementMatchers.anyOf(fieldDescription.asDefined())).matches(fieldDescription), is(true));
    assertThat(ElementMatchers.anyOf(fieldDescription.asDefined()).matches(fieldDescription.asDefined()), is(true));
    assertThat(ElementMatchers.anyOf(fieldDescription.asDefined()).matches(fieldDescription), is(false));
    assertThat(ElementMatchers.anyOf(fieldDescription).matches(fieldDescription.asDefined()), is(false));
}
 
Example #19
Source File: AsmUtils.java    From Diorite with MIT License 5 votes vote down vote up
public static int getReturnCode(TypeDescription fieldType)
{
    if (fieldType.isPrimitive())
    {
        if (BOOLEAN_P.equals(fieldType) || BYTE_P.equals(fieldType) || CHAR_P.equals(fieldType) ||
            SHORT_P.equals(fieldType) || INT_P.equals(fieldType))
        {
            return IRETURN;
        }
        if (LONG_P.equals(fieldType))
        {
            return LRETURN;
        }
        if (FLOAT_P.equals(fieldType))
        {
            return FRETURN;
        }
        if (DOUBLE_P.equals(fieldType))
        {
            return DRETURN;
        }
        else
        {
            throw new IllegalStateException("Unknown store method");
        }
    }
    else
    {
        return ARETURN;
    }
}
 
Example #20
Source File: SpringRestTemplateInstrumentation.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
    return nameStartsWith("org.springframework")
        .and(not(isInterface()))
        // only traverse the object hierarchy if the class declares the method to instrument at all
        .and(declaresMethod(getMethodMatcher()))
        .and(hasSuperType(named("org.springframework.http.client.ClientHttpRequest")));
}
 
Example #21
Source File: FieldDescription.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new latent field description. All provided types are attached to this instance before they are returned.
 *
 * @param declaringType The declaring type of the field.
 * @param token         A token representing the field's shape.
 */
public Latent(TypeDescription declaringType, FieldDescription.Token token) {
    this(declaringType,
            token.getName(),
            token.getModifiers(),
            token.getType(),
            token.getAnnotations());
}
 
Example #22
Source File: MethodConstant.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
    return new Compound(
            ClassConstant.of(methodDescription.getDeclaringType()),
            methodName(),
            ArrayFactory.forType(TypeDescription.Generic.OfNonGenericType.CLASS)
                    .withValues(typeConstantsFor(methodDescription.getParameters().asTypeList().asErasures())),
            MethodInvocation.invoke(accessorMethod())
    ).apply(methodVisitor, implementationContext);
}
 
Example #23
Source File: MethodList.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeElement.Token.TokenList<MethodDescription.Token> asTokenList(ElementMatcher<? super TypeDescription> matcher) {
    List<MethodDescription.Token> tokens = new ArrayList<MethodDescription.Token>(size());
    for (MethodDescription methodDescription : this) {
        tokens.add(methodDescription.asToken(matcher));
    }
    return new ByteCodeElement.Token.TokenList<MethodDescription.Token>(tokens);
}
 
Example #24
Source File: ParameterList.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public ByteCodeElement.Token.TokenList<ParameterDescription.Token> asTokenList(ElementMatcher<? super TypeDescription> matcher) {
    List<ParameterDescription.Token> tokens = new ArrayList<ParameterDescription.Token>(size());
    for (ParameterDescription parameterDescription : this) {
        tokens.add(parameterDescription.asToken(matcher));
    }
    return new ByteCodeElement.Token.TokenList<ParameterDescription.Token>(tokens);
}
 
Example #25
Source File: CustomElementMatchersTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testIncludedPackages() {
    final TypeDescription thisClass = TypeDescription.ForLoadedType.of(getClass());
    assertThat(isInAnyPackage(List.of(), none()).matches(thisClass)).isFalse();
    assertThat(isInAnyPackage(List.of(thisClass.getPackage().getName()), none()).matches(thisClass)).isTrue();
    assertThat(isInAnyPackage(List.of(thisClass.getPackage().getName()), none()).matches(TypeDescription.ForLoadedType.of(Object.class))).isFalse();
}
 
Example #26
Source File: FieldConstantTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testCached() throws Exception {
    StackManipulation stackManipulation = new FieldConstant(fieldDescription).cached();
    assertThat(stackManipulation.isValid(), is(true));
    StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
    assertThat(size.getSizeImpact(), is(1));
    assertThat(size.getMaximalSize(), is(1));
    verify(implementationContext).cache(new FieldConstant(fieldDescription), TypeDescription.ForLoadedType.of(Field.class));
    verifyNoMoreInteractions(implementationContext);
    verify(methodVisitor).visitFieldInsn(Opcodes.GETSTATIC, BAZ, FOO + BAR, QUX + BAZ);
    verifyNoMoreInteractions(methodVisitor);
}
 
Example #27
Source File: MethodGraphCompilerDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDominantInterfaceInheritanceLeft() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(AmbiguousInterfaceBase.DominantInterfaceTargetLeft.class);
    MethodGraph.Linked methodGraph = MethodGraph.Compiler.Default.forJavaHierarchy().compile(typeDescription);
    assertThat(methodGraph.listNodes().size(), is(1));
    MethodDescription methodDescription = TypeDescription.ForLoadedType.of(AmbiguousInterfaceBase.DominantIntermediate.class)
            .getDeclaredMethods().getOnly();
    MethodGraph.Node node = methodGraph.locate(methodDescription.asSignatureToken());
    assertThat(node.getSort(), is(MethodGraph.Node.Sort.RESOLVED));
    assertThat(node.getMethodTypes().size(), is(1));
    assertThat(node.getMethodTypes().contains(methodDescription.asTypeToken()), is(true));
    assertThat(node.getRepresentative(), is(methodDescription));
    assertThat(node.getVisibility(), is(methodDescription.getVisibility()));
}
 
Example #28
Source File: StubValueBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testVoidReturnType() throws Exception {
    when(target.getType()).thenReturn(TypeDescription.Generic.OBJECT);
    when(source.getReturnType()).thenReturn(TypeDescription.Generic.VOID);
    assertThat(StubValue.Binder.INSTANCE.bind(annotationDescription,
            source,
            target,
            implementationTarget,
            assigner,
            Assigner.Typing.STATIC).isValid(), is(true));
}
 
Example #29
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsParameterDefinedShape() throws Exception {
    ParameterDescription parameterDescription = TypeDescription.ForLoadedType.of(GenericMethodType.Inner.class).getInterfaces().getOnly()
            .getDeclaredMethods().filter(named(FOO)).getOnly().getParameters().getOnly();
    assertThat(ElementMatchers.definedParameter(ElementMatchers.is(parameterDescription.asDefined())).matches(parameterDescription), is(true));
    assertThat(ElementMatchers.is(parameterDescription.asDefined()).matches(parameterDescription.asDefined()), is(true));
    assertThat(ElementMatchers.is(parameterDescription.asDefined()).matches(parameterDescription), is(true));
    assertThat(ElementMatchers.is(parameterDescription).matches(parameterDescription.asDefined()), is(false));
}
 
Example #30
Source File: MethodCall.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Defines the given types to be provided as arguments to the invoked method where the represented types
 * are stored in the generated class's constant pool.
 *
 * @param typeDescription The type descriptions to provide as arguments.
 * @return A method call that hands the provided arguments to the invoked method.
 */
public MethodCall with(TypeDescription... typeDescription) {
    List<ArgumentLoader.Factory> argumentLoaders = new ArrayList<ArgumentLoader.Factory>(typeDescription.length);
    for (TypeDescription aTypeDescription : typeDescription) {
        argumentLoaders.add(new ArgumentLoader.ForStackManipulation(ClassConstant.of(aTypeDescription), Class.class));
    }
    return with(argumentLoaders);
}