net.bytebuddy.description.type.TypeDefinition Java Examples

The following examples show how to use net.bytebuddy.description.type.TypeDefinition. 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
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    when(getterMethod.getDeclaringType()).thenReturn(getterType);
    when(setterMethod.getDeclaringType()).thenReturn(setterType);
    when(instrumentedType.getDeclaredFields()).thenReturn(new FieldList.Explicit<FieldDescription.InDefinedShape>(fieldDescription));
    when(fieldDescription.getType()).thenReturn(genericFieldType);
    when(genericFieldType.getSort()).thenReturn(TypeDefinition.Sort.NON_GENERIC);
    when(genericFieldType.getStackSize()).thenReturn(StackSize.ZERO);
    when(genericFieldType.asErasure()).thenReturn(fieldType);
    when(fieldType.getSort()).thenReturn(TypeDefinition.Sort.NON_GENERIC);
    when(fieldType.asErasure()).thenReturn(fieldType);
    when(fieldType.getInternalName()).thenReturn(FOO);
    when(genericSetterType.asErasure()).thenReturn(setterType);
    when(genericGetterType.asErasure()).thenReturn(getterType);
}
 
Example #2
Source File: AbstractDynamicTypeBuilderTest.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Test
@JavaVersionRule.Enforce(8)
public void testGenericMethodDefinitionMetaDataParameter() throws Exception {
    Class<?> type = createPlain()
            .defineMethod(QUX, list)
            .withParameter(list, BAR, ProvisioningState.MANDATED)
            .throwing(fooVariable)
            .typeVariable(FOO, Exception.class)
            .intercept(StubMethod.INSTANCE)
            .make()
            .load(new URLClassLoader(new URL[0], null), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
    assertThat(TypeDefinition.Sort.describe(type).getDeclaredMethods().filter(named(QUX)).getOnly().getParameters().getOnly().getName(), is(BAR));
    assertThat(TypeDefinition.Sort.describe(type).getDeclaredMethods().filter(named(QUX)).getOnly().getParameters().getOnly().getModifiers(),
            is(ProvisioningState.MANDATED.getMask()));
}
 
Example #3
Source File: PropertyMutatorCollector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
protected StackManipulation invocationOperation(AnnotatedMember annotatedMember,
        TypeDefinition beanClassDescription) {

    final String methodName = annotatedMember.getName();
    @SuppressWarnings("unchecked")
    final MethodList<MethodDescription> matchingMethods =
            (MethodList<MethodDescription>) beanClassDescription.getDeclaredMethods().filter(named(methodName));

    if (matchingMethods.size() == 1) { //method was declared on class
        return MethodInvocation.invoke(matchingMethods.getOnly());
    }
    if (matchingMethods.isEmpty()) { //method was not found on class, try super class
        return invocationOperation(annotatedMember, beanClassDescription.getSuperClass());
    }
    else { //should never happen
        throw new IllegalStateException("Could not find definition of method: " + methodName);
    }

}
 
Example #4
Source File: MemberSubstitution.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodDescription resolve(TypeDescription targetType, ByteCodeElement target, TypeList.Generic parameters, TypeDescription.Generic result) {
    if (parameters.isEmpty()) {
        throw new IllegalStateException("Cannot substitute parameterless instruction with " + target);
    } else if (parameters.get(0).isPrimitive() || parameters.get(0).isArray()) {
        throw new IllegalStateException("Cannot invoke method on primitive or array type for " + target);
    }
    TypeDefinition typeDefinition = parameters.get(0);
    List<MethodDescription> candidates = CompoundList.<MethodDescription>of(methodGraphCompiler.compile(typeDefinition, instrumentedType)
            .listNodes()
            .asMethodList()
            .filter(matcher), typeDefinition.getDeclaredMethods().filter(isPrivate().<MethodDescription>and(isVisibleTo(instrumentedType)).and(matcher)));
    if (candidates.size() == 1) {
        return candidates.get(0);
    } else {
        throw new IllegalStateException("Not exactly one method that matches " + matcher + ": " + candidates);
    }
}
 
Example #5
Source File: HashCodeAndEqualsPlugin.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
@Override
protected EqualsMethod equalsMethod(TypeDescription instrumentedType) {
    TypeDefinition typeDefinition = instrumentedType.getSuperClass();
    while (typeDefinition != null && !typeDefinition.represents(Object.class)) {
        if (typeDefinition.asErasure().getDeclaredAnnotations().isAnnotationPresent(Enhance.class)) {
            return EqualsMethod.requiringSuperClassEquality();
        }
        MethodList<?> hashCode = typeDefinition.getDeclaredMethods().filter(isHashCode());
        if (!hashCode.isEmpty()) {
            return hashCode.getOnly().isAbstract()
                    ? EqualsMethod.isolated()
                    : EqualsMethod.requiringSuperClassEquality();
        }
        typeDefinition = typeDefinition.getSuperClass().asErasure();
    }
    return EqualsMethod.isolated();
}
 
Example #6
Source File: ArrayFactory.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a suitable array creator for the given component type.
 *
 * @param componentType The component type of the array to be created.
 * @return A suitable array creator.
 */
private static ArrayCreator makeArrayCreatorFor(TypeDefinition componentType) {
    if (!componentType.isPrimitive()) {
        return new ArrayCreator.ForReferenceType(componentType.asErasure());
    } else if (componentType.represents(boolean.class)) {
        return ArrayCreator.ForPrimitiveType.BOOLEAN;
    } else if (componentType.represents(byte.class)) {
        return ArrayCreator.ForPrimitiveType.BYTE;
    } else if (componentType.represents(short.class)) {
        return ArrayCreator.ForPrimitiveType.SHORT;
    } else if (componentType.represents(char.class)) {
        return ArrayCreator.ForPrimitiveType.CHARACTER;
    } else if (componentType.represents(int.class)) {
        return ArrayCreator.ForPrimitiveType.INTEGER;
    } else if (componentType.represents(long.class)) {
        return ArrayCreator.ForPrimitiveType.LONG;
    } else if (componentType.represents(float.class)) {
        return ArrayCreator.ForPrimitiveType.FLOAT;
    } else if (componentType.represents(double.class)) {
        return ArrayCreator.ForPrimitiveType.DOUBLE;
    } else {
        throw new IllegalArgumentException("Cannot create array of type " + componentType);
    }
}
 
Example #7
Source File: HasSuperTypeMatcher.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean matches(T target) {
    Set<TypeDescription> previous = new HashSet<TypeDescription>();
    for (TypeDefinition typeDefinition : target) {
        if (!previous.add(typeDefinition.asErasure())) { // Main type can be an interface.
            return false; // Avoids a life-lock when encountering a recursive type-definition.
        } else if (matcher.matches(typeDefinition.asGenericType())) {
            return true;
        }
        LinkedList<TypeDefinition> interfaceTypes = new LinkedList<TypeDefinition>(typeDefinition.getInterfaces());
        while (!interfaceTypes.isEmpty()) {
            TypeDefinition interfaceType = interfaceTypes.removeFirst();
            if (previous.add(interfaceType.asErasure())) {
                if (matcher.matches(interfaceType.asGenericType())) {
                    return true;
                } else {
                    interfaceTypes.addAll(interfaceType.getInterfaces());
                }
            }
        }
    }
    return false;
}
 
Example #8
Source File: PersistentAttributeTransformer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private static Collection<FieldDescription> collectInheritPersistentFields(
		TypeDefinition managedCtClass,
		ByteBuddyEnhancementContext enhancementContext) {
	if ( managedCtClass == null || managedCtClass.represents( Object.class ) ) {
		return Collections.emptyList();
	}
	TypeDefinition managedCtSuperclass = managedCtClass.getSuperClass();

	if ( !enhancementContext.isMappedSuperclassClass( managedCtSuperclass.asErasure() ) ) {
		return collectInheritPersistentFields( managedCtSuperclass, enhancementContext );
	}
	log.debugf( "Found @MappedSuperclass %s to collectPersistenceFields", managedCtSuperclass );
	List<FieldDescription> persistentFieldList = new ArrayList<FieldDescription>();

	for ( FieldDescription ctField : managedCtSuperclass.getDeclaredFields() ) {
		if ( ctField.getName().startsWith( "$$_hibernate_" ) || "this$0".equals( ctField.getName() ) ) {
			continue;
		}
		if ( !ctField.isStatic() && enhancementContext.isPersistentField( ctField ) ) {
			persistentFieldList.add( ctField );
		}
	}
	persistentFieldList.addAll( collectInheritPersistentFields( managedCtSuperclass, enhancementContext ) );
	return persistentFieldList;
}
 
Example #9
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodGraph.Linked compile(TypeDefinition typeDefinition, TypeDescription viewPoint) {
    Map<TypeDefinition, Key.Store<T>> snapshots = new HashMap<TypeDefinition, Key.Store<T>>();
    Key.Store<?> rootStore = doAnalyze(typeDefinition, snapshots, isVirtual().and(isVisibleTo(viewPoint)));
    TypeDescription.Generic superClass = typeDefinition.getSuperClass();
    List<TypeDescription.Generic> interfaceTypes = typeDefinition.getInterfaces();
    Map<TypeDescription, MethodGraph> interfaceGraphs = new HashMap<TypeDescription, MethodGraph>();
    for (TypeDescription.Generic interfaceType : interfaceTypes) {
        interfaceGraphs.put(interfaceType.asErasure(), snapshots.get(interfaceType).asGraph(merger));
    }
    return new Linked.Delegation(rootStore.asGraph(merger),
            superClass == null
                    ? Empty.INSTANCE
                    : snapshots.get(superClass).asGraph(merger),
            interfaceGraphs);
}
 
Example #10
Source File: ByteBuddyProcessFunctionInvoker.java    From da-streamingledger with Apache License 2.0 6 votes vote down vote up
private static <InT, OutT> DynamicType.Unloaded<?> createDynamicTypeFromSpec(StreamingLedgerSpec<InT, OutT> spec)
        throws NoSuchMethodException {
    PackageLocalNamingStrategy generatedTypeName = new PackageLocalNamingStrategy(spec.processFunction.getClass());

    TypeDefinition generatedType = Generic.Builder.parameterizedType(
            ProcessFunctionInvoker.class,
            spec.inputType.getTypeClass(),
            spec.resultType.getTypeClass()
    ).build();

    TypeDefinition processFunctionType = new TypeDescription.ForLoadedType(spec.processFunction.getClass());
    ForLoadedConstructor superTypeConstructor =
            new ForLoadedConstructor(ProcessFunctionInvoker.class.getDeclaredConstructor());
    MethodDescription processMethodType = processMethodTypeFromSpec(spec);

    Builder<?> builder = configureByteBuddyBuilder(
            generatedTypeName,
            generatedType,
            processFunctionType,
            superTypeConstructor,
            processMethodType,
            spec.stateBindings.size());

    return builder.make();
}
 
Example #11
Source File: CollectionErasureMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean matches(T target) {
    List<TypeDescription> typeDescriptions = new ArrayList<TypeDescription>();
    for (TypeDefinition typeDefinition : target) {
        typeDescriptions.add(typeDefinition.asErasure());
    }
    return matcher.matches(typeDescriptions);
}
 
Example #12
Source File: EqualsMethod.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a type definition to a equality comparison.
 *
 * @param typeDefinition The type definition to resolve.
 * @return The stack manipulation to apply.
 */
public static StackManipulation of(TypeDefinition typeDefinition) {
    if (typeDefinition.represents(boolean.class)
            || typeDefinition.represents(byte.class)
            || typeDefinition.represents(short.class)
            || typeDefinition.represents(char.class)
            || typeDefinition.represents(int.class)) {
        return ConditionalReturn.onNonEqualInteger();
    } else if (typeDefinition.represents(long.class)) {
        return new Compound(LONG, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(float.class)) {
        return new Compound(FLOAT, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(double.class)) {
        return new Compound(DOUBLE, ConditionalReturn.onNonZeroInteger());
    } else if (typeDefinition.represents(boolean[].class)) {
        return new Compound(BOOLEAN_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(byte[].class)) {
        return new Compound(BYTE_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(short[].class)) {
        return new Compound(SHORT_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(char[].class)) {
        return new Compound(CHARACTER_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(int[].class)) {
        return new Compound(INTEGER_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(long[].class)) {
        return new Compound(LONG_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(float[].class)) {
        return new Compound(FLOAT_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.represents(double[].class)) {
        return new Compound(DOUBLE_ARRAY, ConditionalReturn.onZeroInteger());
    } else if (typeDefinition.isArray()) {
        return new Compound(typeDefinition.getComponentType().isArray()
                ? NESTED_ARRAY
                : REFERENCE_ARRAY, ConditionalReturn.onZeroInteger());
    } else {
        return new Compound(MethodInvocation.invoke(EQUALS).virtual(typeDefinition.asErasure()), ConditionalReturn.onZeroInteger());
    }
}
 
Example #13
Source File: TransformerForMethodTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(returnType.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(returnType);
    when(typeVariableBound.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(typeVariableBound);
    when(parameterType.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(parameterType);
    when(exceptionType.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(exceptionType);
    when(typeVariableBound.getSymbol()).thenReturn(QUX);
    when(typeVariableBound.getSort()).thenReturn(TypeDefinition.Sort.VARIABLE);
    when(typeVariableBound.asGenericType()).thenReturn(typeVariableBound);
    when(methodDescription.asToken(matchesPrototype(none()))).thenReturn(methodToken);
    when(methodDescription.getDeclaringType()).thenReturn(declaringType);
    when(methodDescription.asDefined()).thenReturn(definedMethod);
    when(methodToken.getName()).thenReturn(FOO);
    when(methodToken.getModifiers()).thenReturn(MODIFIERS);
    when(methodToken.getReturnType()).thenReturn(returnType);
    when(methodToken.getTypeVariableTokens())
            .thenReturn(new ByteCodeElement.Token.TokenList<TypeVariableToken>(new TypeVariableToken(QUX, new TypeList.Generic.Explicit(typeVariableBound))));
    when(methodToken.getExceptionTypes()).thenReturn(new TypeList.Generic.Explicit(exceptionType));
    when(methodToken.getParameterTokens())
            .thenReturn(new ByteCodeElement.Token.TokenList<ParameterDescription.Token>(parameterToken));
    when(methodToken.getAnnotations()).thenReturn(new AnnotationList.Explicit(methodAnnotation));
    when(modifierContributor.getMask()).thenReturn(MASK);
    when(modifierContributor.getRange()).thenReturn(RANGE);
    when(parameterToken.getType()).thenReturn(parameterType);
    when(parameterToken.getAnnotations()).thenReturn(new AnnotationList.Explicit(parameterAnnotation));
    when(parameterToken.getName()).thenReturn(BAR);
    when(parameterToken.getModifiers()).thenReturn(MODIFIERS * 2);
    when(definedMethod.getParameters())
            .thenReturn(new ParameterList.Explicit<ParameterDescription.InDefinedShape>(definedParameter));
    when(declaringType.asErasure()).thenReturn(rawDeclaringType);
    when(returnType.asErasure()).thenReturn(rawReturnType);
    when(parameterType.asErasure()).thenReturn(rawParameterType);
    when(exceptionType.asGenericType()).thenReturn(exceptionType);
}
 
Example #14
Source File: Transformer.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new transformed method.
 *
 * @param instrumentedType  The instrumented type for which this method is transformed.
 * @param declaringType     The method's declaring type.
 * @param token             The method representing the transformed method.
 * @param methodDescription The defined shape of the transformed method.
 */
protected TransformedMethod(TypeDescription instrumentedType,
                            TypeDefinition declaringType,
                            Token token,
                            InDefinedShape methodDescription) {
    this.instrumentedType = instrumentedType;
    this.declaringType = declaringType;
    this.token = token;
    this.methodDescription = methodDescription;
}
 
Example #15
Source File: HasSuperClassMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(superType.asGenericType()).thenReturn(superType);
    when(interfaceType.asGenericType()).thenReturn(interfaceType);
    when(interfaceType.asErasure()).thenReturn(mock(TypeDescription.class));
    when(implicitInterfaceType.asGenericType()).thenReturn(implicitInterfaceType);
    when(implicitInterfaceType.asErasure()).thenReturn(mock(TypeDescription.class));
    when(typeDescription.iterator()).thenReturn(Collections.<TypeDefinition>singletonList(superType).iterator());
    when(superType.getInterfaces()).thenReturn(new TypeList.Generic.Explicit(interfaceType));
    when(interfaceType.getInterfaces()).thenReturn(new TypeList.Generic.Explicit(implicitInterfaceType));
    when(implicitInterfaceType.getInterfaces()).thenReturn(new TypeList.Generic.Empty());
}
 
Example #16
Source File: ImmutableProxy.java    From reflection-util with Apache License 2.0 5 votes vote down vote up
private static ElementMatcher<MethodDescription> isAnnotatedWith(Class<? extends Annotation> annotation) {
	return target -> {
		TypeDefinition type = target.getDeclaringType();
		SignatureToken methodSignature = target.asSignatureToken();
		return isAnnotatedWith(methodSignature, type, annotation);
	};
}
 
Example #17
Source File: MethodOverrideMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean matches(T target) {
    Set<TypeDescription> duplicates = new HashSet<TypeDescription>();
    for (TypeDefinition typeDefinition : target.getDeclaringType()) {
        if (matches(target, typeDefinition) || matches(target, typeDefinition.getInterfaces(), duplicates)) {
            return true;
        }
    }
    return false;
}
 
Example #18
Source File: MethodOverrideMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Matches a method against a list of types.
 *
 * @param target          The method that is matched as a target.
 * @param typeDefinitions The type definitions to check if they declare a method with the same signature as {@code target}.
 * @param duplicates      A set containing duplicate interfaces that do not need to be revisited.
 * @return {@code true} if any type defines a method with the same signature as the {@code target} method.
 */
private boolean matches(MethodDescription target, List<? extends TypeDefinition> typeDefinitions, Set<TypeDescription> duplicates) {
    for (TypeDefinition anInterface : typeDefinitions) {
        if (duplicates.add(anInterface.asErasure()) && (matches(target, anInterface) || matches(target, anInterface.getInterfaces(), duplicates))) {
            return true;
        }
    }
    return false;
}
 
Example #19
Source File: MethodOverrideMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a type declares a method with the same signature as {@code target}.
 *
 * @param target         The method to be checked.
 * @param typeDefinition The type to check for declaring a method with the same signature as {@code target}.
 * @return {@code true} if the supplied type declares a compatible method.
 */
private boolean matches(MethodDescription target, TypeDefinition typeDefinition) {
    for (MethodDescription methodDescription : typeDefinition.getDeclaredMethods().filter(isVirtual())) {
        if (methodDescription.asSignatureToken().equals(target.asSignatureToken())) {
            if (matcher.matches(typeDefinition.asGenericType())) {
                return true;
            } else {
                break;
            }
        }
    }
    return false;
}
 
Example #20
Source File: MethodInheritanceAnnotationMatcher.java    From skywalking with Apache License 2.0 5 votes vote down vote up
private boolean recursiveMatches(TypeDefinition typeDefinition, String methodName, ParameterList<?> parameters) {
    TypeList.Generic interfaces = typeDefinition.getInterfaces();
    for (TypeDescription.Generic implInterface : interfaces) {
        if (recursiveMatches(implInterface, methodName, parameters)) {
            return true;
        }
        MethodList<MethodDescription.InGenericShape> declaredMethods = implInterface.getDeclaredMethods();
        for (MethodDescription declaredMethod : declaredMethods) {
            if (Objects.equals(declaredMethod.getName(), methodName) && parameterEquals(parameters, declaredMethod.getParameters())) {
                return matcher.matches(declaredMethod.getDeclaredAnnotations());
            }
        }
    }
    return false;
}
 
Example #21
Source File: HasSuperClassMatcher.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean matches(T target) {
    if (target.isInterface()) {
        return matcher.matches(TypeDescription.Generic.OBJECT);
    }
    for (TypeDefinition typeDefinition : target) {
        if (matcher.matches(typeDefinition.asGenericType())) {
            return true;
        }
    }
    return false;
}
 
Example #22
Source File: ElementMatchersTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testTakesArgumentsGeneric() throws Exception {
    assertThat(ElementMatchers.takesGenericArguments(GenericMethodType.class.getTypeParameters()[0])
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(true));
    assertThat(ElementMatchers.takesGenericArguments(TypeDefinition.Sort.describe(GenericMethodType.class.getTypeParameters()[0]))
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(true));
    assertThat(ElementMatchers.takesGenericArguments(Exception.class)
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(false));
    assertThat(ElementMatchers.takesGenericArguments(Collections.singletonList(TypeDescription.ForLoadedType.of(Exception.class)))
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(false));
    assertThat(ElementMatchers.takesArguments(Exception.class)
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(true));
    assertThat(ElementMatchers.takesArguments(Collections.singletonList(TypeDescription.ForLoadedType.of(Exception.class)))
            .matches(new MethodDescription.ForLoadedMethod(GenericMethodType.class.getDeclaredMethod(FOO, Exception.class))), is(true));
}
 
Example #23
Source File: MethodGraph.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Analyzes the given type description without checking if it is already presented in the key store.
 *
 * @param typeDefinition   The type to analyze.
 * @param snapshots        A map containing snapshots of key stores for previously analyzed types.
 * @param relevanceMatcher A matcher for filtering methods that should be included in the graph.
 * @return A key store describing the provided type.
 */
protected Key.Store<T> doAnalyze(TypeDefinition typeDefinition,
                                 Map<TypeDefinition, Key.Store<T>> snapshots,
                                 ElementMatcher<? super MethodDescription> relevanceMatcher) {
    Key.Store<T> store = analyzeNullable(typeDefinition.getSuperClass(), snapshots, relevanceMatcher);
    Key.Store<T> interfaceStore = new Key.Store<T>();
    for (TypeDescription.Generic interfaceType : typeDefinition.getInterfaces()) {
        interfaceStore = interfaceStore.combineWith(analyze(interfaceType.accept(visitor), interfaceType, snapshots, relevanceMatcher));
    }
    return store.inject(interfaceStore).registerTopLevel(typeDefinition.getDeclaredMethods().filter(relevanceMatcher), harmonizer);
}
 
Example #24
Source File: OriginBinderTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringBinding() throws Exception {
    when(targetType.getInternalName()).thenReturn(FOO);
    when(targetType.represents(String.class)).thenReturn(true);
    when(targetType.getSort()).thenReturn(TypeDefinition.Sort.NON_GENERIC);
    MethodDelegationBinder.ParameterBinding<?> parameterBinding = Origin.Binder.INSTANCE
            .bind(annotationDescription, source, target, implementationTarget, assigner, Assigner.Typing.STATIC);
    assertThat(parameterBinding.isValid(), is(true));
}
 
Example #25
Source File: ErasureMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatch() throws Exception {
    when(elementMatcher.matches(typeDescription)).thenReturn(true);
    when(typeDefinition.getSort()).thenReturn(TypeDefinition.Sort.NON_GENERIC);
    assertThat(new ErasureMatcher<TypeDefinition>(elementMatcher).matches(typeDefinition), is(true));
    verify(typeDefinition).asErasure();
    verifyNoMoreInteractions(typeDefinition);
    verify(elementMatcher).matches(typeDescription);
    verifyNoMoreInteractions(elementMatcher);
    verifyZeroInteractions(typeDescription);
}
 
Example #26
Source File: TransformerForMethodTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetainsInstrumentedType() throws Exception {
    TypeDescription typeDescription = TypeDescription.ForLoadedType.of(Bar.class);
    MethodDescription methodDescription = typeDescription.getSuperClass().getDeclaredMethods().filter(named(BAR)).getOnly();
    MethodDescription transformed = Transformer.ForMethod.withModifiers().transform(typeDescription, methodDescription);
    assertThat(transformed, is(methodDescription));
    assertThat(transformed.getModifiers(), is(methodDescription.getModifiers()));
    assertThat(transformed.getReturnType().asErasure(), is(typeDescription));
    assertThat(transformed.getReturnType().getSort(), is(TypeDefinition.Sort.PARAMETERIZED));
    assertThat(transformed.getReturnType().getTypeArguments().size(), is(1));
    assertThat(transformed.getReturnType().getTypeArguments().getOnly(), is(typeDescription.getSuperClass().getDeclaredMethods().filter(named(FOO)).getOnly().getReturnType()));
}
 
Example #27
Source File: FieldLocator.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
protected FieldList<?> locate(ElementMatcher<? super FieldDescription> matcher) {
    for (TypeDefinition typeDefinition : typeDescription) {
        FieldList<?> candidates = typeDefinition.getDeclaredFields().filter(matcher);
        if (!candidates.isEmpty()) {
            return candidates;
        }
    }
    return new FieldList.Empty<FieldDescription>();
}
 
Example #28
Source File: CollectionErasureMatcherTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoMatch() throws Exception {
    assertThat(new CollectionErasureMatcher<Iterable<TypeDefinition>>(matcher).matches(Arrays.asList(first, second)), is(false));
    verify(matcher).matches(Arrays.asList(firstRaw, secondRaw));
    verifyNoMoreInteractions(matcher);
    verify(first).asErasure();
    verifyNoMoreInteractions(first);
    verify(second).asErasure();
    verifyNoMoreInteractions(second);
}
 
Example #29
Source File: ModelClassEnhancer.java    From activejpa with Apache License 2.0 5 votes vote down vote up
/**
 * @param builder
 * @param typeDescription
 * @param classLoader
 * @param name
 * @param targetType
 * @param parameters
 * @return
 */
private Builder<?> defineMethod(Builder<?> builder, TypeDescription typeDescription, ClassLoader classLoader, String name, TypeDefinition targetType, TypeDefinition... parameters) {
    logger.info("Defining the method - {}.{} with return type - {} and parameters - {}", typeDescription.getActualName(), name, targetType.getActualName(), parameters);
    try {
        builder = builder.defineMethod(name, targetType, Ownership.STATIC, Visibility.PUBLIC).withParameters(parameters).intercept(MethodDelegation.to(ModelInterceptor.class));
        builder.make();
    } catch (Exception exception) {
        if (! (exception.getCause() instanceof NoSuchMethodException)) {
            logger.error("Failed while defining the method - {}.{}", typeDescription.getActualName(), name, exception);
            throw new AssertionError(exception);
        }
    }
    return builder;
}
 
Example #30
Source File: AbstractMethodDescriptionTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericTypes() throws Exception {
    assertThat(describe(genericMethod).getReturnType(), is(TypeDefinition.Sort.describe(genericMethod.getGenericReturnType())));
    assertThat(describe(genericMethod).getParameters().asTypeList(),
            is((TypeList.Generic) new TypeList.Generic.ForLoadedTypes(genericMethod.getGenericParameterTypes())));
    assertThat(describe(genericMethod).getExceptionTypes(),
            is((TypeList.Generic) new TypeList.Generic.ForLoadedTypes(genericMethod.getGenericExceptionTypes())));
}