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 Project: lams   Author: lamsfoundation   File: BiDirectionalAssociationHandler.java    License: 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 #2
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: 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 Project: byte-buddy   Author: raphw   File: FieldProxyBinderTest.java    License: 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 #4
Source Project: skywalking   Author: apache   File: SkyWalkingAgent.java    License: 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 #5
Source Project: byte-buddy   Author: raphw   File: ElementMatchersTest.java    License: 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 #6
Source Project: byte-buddy   Author: raphw   File: PipeBinderTest.java    License: 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 #7
Source Project: byte-buddy   Author: raphw   File: MethodInvocationGenericTest.java    License: 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 #8
Source Project: byte-buddy   Author: raphw   File: AsmVisitorWrapperNoOpTest.java    License: 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 #9
Source Project: apm-agent-java   Author: elastic   File: JobTransactionNameInstrumentation.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ElementMatcher<? super TypeDescription> getTypeMatcher() {
    return isInAnyPackage(applicationPackages, ElementMatchers.<NamedElement>none())
        .or(nameStartsWith("org.quartz.job"))
        .and(hasSuperType(named("org.quartz.Job")))
        .and(declaresMethod(getMethodMatcher()));
}
 
Example #10
Source Project: byte-buddy   Author: raphw   File: ElementMatchersTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsAnnotatedWith() throws Exception {
    assertThat(ElementMatchers.isAnnotatedWith(IsAnnotatedWithAnnotation.class)
            .matches(TypeDescription.ForLoadedType.of(IsAnnotatedWith.class)), is(true));
    assertThat(ElementMatchers.isAnnotatedWith(IsAnnotatedWithAnnotation.class)
            .matches(TypeDescription.OBJECT), is(false));
}
 
Example #11
Source Project: byte-buddy   Author: raphw   File: InvokeDynamicTest.java    License: 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 #12
Source Project: byte-buddy   Author: raphw   File: EqualsMethodOtherTest.java    License: 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 #13
Source Project: byte-buddy   Author: raphw   File: JavaConstant.java    License: 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 #14
Source Project: Diorite   Author: Diorite   File: Controller.java    License: 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 #15
Source Project: byte-buddy   Author: raphw   File: ElementMatchersTest.java    License: 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 #16
Source Project: byte-buddy   Author: raphw   File: StubValueBinderTest.java    License: 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 #17
Source Project: Diorite   Author: Diorite   File: AsmUtils.java    License: 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 #18
Source Project: apm-agent-java   Author: elastic   File: SpringRestTemplateInstrumentation.java    License: 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 #19
Source Project: byte-buddy   Author: raphw   File: MethodConstant.java    License: 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 #20
Source Project: byte-buddy   Author: raphw   File: MethodList.java    License: 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 #21
Source Project: apm-agent-java   Author: elastic   File: CustomElementMatchersTest.java    License: 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 #22
Source Project: byte-buddy   Author: raphw   File: MethodGraphCompilerDefaultTest.java    License: 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 #23
Source Project: byte-buddy   Author: raphw   File: StubValueBinderTest.java    License: 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 #24
Source Project: byte-buddy   Author: raphw   File: ElementMatchersTest.java    License: 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 #25
Source Project: byte-buddy   Author: raphw   File: MethodCall.java    License: 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);
}
 
Example #26
Source Project: byte-buddy   Author: raphw   File: FieldConstantTest.java    License: 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 Project: byte-buddy   Author: raphw   File: ParameterList.java    License: 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 #28
Source Project: byte-buddy   Author: raphw   File: FieldDescription.java    License: 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 #29
Source Project: byte-buddy   Author: raphw   File: JavaTypeTest.java    License: 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 #30
Source Project: byte-buddy   Author: raphw   File: MethodGraph.java    License: 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());
}