Java Code Examples for net.bytebuddy.description.type.TypeDefinition

The following examples show how to use net.bytebuddy.description.type.TypeDefinition. These examples are extracted from open source projects. 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: da-streamingledger   Author: dataArtisans   File: ByteBuddyProcessFunctionInvoker.java    License: 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 #2
Source Project: lams   Author: lamsfoundation   File: PersistentAttributeTransformer.java    License: 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 #3
Source Project: jackson-modules-base   Author: FasterXML   File: PropertyMutatorCollector.java    License: 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 Project: byte-buddy   Author: raphw   File: MethodGraph.java    License: 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 #5
Source Project: byte-buddy   Author: raphw   File: HasSuperTypeMatcher.java    License: 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 #6
Source Project: byte-buddy   Author: raphw   File: ArrayFactory.java    License: 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 Project: byte-buddy   Author: raphw   File: MemberSubstitution.java    License: 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 #8
Source Project: byte-buddy   Author: raphw   File: AbstractDynamicTypeBuilderTest.java    License: 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 #9
Source Project: byte-buddy   Author: raphw   File: FieldProxyBinderTest.java    License: 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 #10
Source Project: byte-buddy   Author: raphw   File: HashCodeAndEqualsPlugin.java    License: 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 #11
Source Project: byte-buddy   Author: raphw   File: FieldDescriptionLatentTest.java    License: Apache License 2.0 5 votes vote down vote up
protected FieldDescription.InDefinedShape describe(Field field) {
    return new FieldDescription.Latent(TypeDescription.ForLoadedType.of(field.getDeclaringClass()),
            field.getName(),
            field.getModifiers(),
            TypeDefinition.Sort.describe(field.getGenericType()),
            new AnnotationList.ForLoadedAnnotations(field.getDeclaredAnnotations()));
}
 
Example #12
Source Project: byte-buddy   Author: raphw   File: AbstractMethodDescriptionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGenericTypesOfMethodWithoutException() throws Exception {
    assertThat(describe(genericMethodWithRawException).getReturnType(),
            is(TypeDefinition.Sort.describe(genericMethodWithRawException.getGenericReturnType())));
    assertThat(describe(genericMethodWithRawException).getParameters().asTypeList(),
            is((TypeList.Generic) new TypeList.Generic.ForLoadedTypes(genericMethodWithRawException.getGenericParameterTypes())));
    assertThat(describe(genericMethodWithRawException).getExceptionTypes(),
            is((TypeList.Generic) new TypeList.Generic.ForLoadedTypes(genericMethodWithRawException.getGenericExceptionTypes())));
}
 
Example #13
Source Project: byte-buddy   Author: raphw   File: HasSuperClassMatcherTest.java    License: 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 #14
Source Project: reflection-util   Author: cronn-de   File: ImmutableProxy.java    License: 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 #15
Source Project: byte-buddy   Author: raphw   File: EqualsMethod.java    License: 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 #16
Source Project: byte-buddy   Author: raphw   File: TransformerForMethodTest.java    License: 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 #17
Source Project: byte-buddy   Author: raphw   File: Transformer.java    License: 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 #18
Source Project: jackson-modules-base   Author: FasterXML   File: BeanBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private DynamicType.Builder<?> createGetter(DynamicType.Builder<?> builder,
                                            POJOProperty property,
                                            TypeDefinition typeDefinition)
{
    final String methodName = property.getGetter() != null
            ? property.getGetter().getName() //if the getter exists, use it's name because it could be like 'isXXX'
            : buildGetterName(property.getName());
    return builder
                .defineMethod(methodName, typeDefinition)
                .intercept(FieldAccessor.ofBeanProperty());
}
 
Example #19
Source Project: byte-buddy   Author: raphw   File: HashCodeMethod.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a type definition to a hash code.
 *
 * @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 Trivial.INSTANCE;
    } else if (typeDefinition.represents(long.class)) {
        return LONG;
    } else if (typeDefinition.represents(float.class)) {
        return FLOAT;
    } else if (typeDefinition.represents(double.class)) {
        return DOUBLE;
    } else if (typeDefinition.represents(boolean[].class)) {
        return BOOLEAN_ARRAY;
    } else if (typeDefinition.represents(byte[].class)) {
        return BYTE_ARRAY;
    } else if (typeDefinition.represents(short[].class)) {
        return SHORT_ARRAY;
    } else if (typeDefinition.represents(char[].class)) {
        return CHARACTER_ARRAY;
    } else if (typeDefinition.represents(int[].class)) {
        return INTEGER_ARRAY;
    } else if (typeDefinition.represents(long[].class)) {
        return LONG_ARRAY;
    } else if (typeDefinition.represents(float[].class)) {
        return FLOAT_ARRAY;
    } else if (typeDefinition.represents(double[].class)) {
        return DOUBLE_ARRAY;
    } else if (typeDefinition.isArray()) {
        return typeDefinition.getComponentType().isArray()
                ? NESTED_ARRAY
                : REFERENCE_ARRAY;
    } else {
        return MethodInvocation.invoke(HASH_CODE).virtual(typeDefinition.asErasure());
    }
}
 
Example #20
Source Project: skywalking   Author: apache   File: MethodInheritanceAnnotationMatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(T target) {
    if (matcher.matches(target.getDeclaredAnnotations())) {
        return true;
    }
    String name = target.getName();
    ParameterList<?> parameters = target.getParameters();

    TypeDefinition declaringType = target.getDeclaringType();
    return recursiveMatches(declaringType, name, parameters);
}
 
Example #21
Source Project: skywalking   Author: apache   File: MethodInheritanceAnnotationMatcher.java    License: 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 #22
Source Project: byte-buddy   Author: raphw   File: CollectionErasureMatcher.java    License: 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 #23
Source Project: byte-buddy   Author: raphw   File: MethodOverrideMatcher.java    License: 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 #24
Source Project: byte-buddy   Author: raphw   File: MethodOverrideMatcher.java    License: 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 #25
Source Project: byte-buddy   Author: raphw   File: MethodOverrideMatcher.java    License: 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 #26
Source Project: byte-buddy   Author: raphw   File: HasSuperClassMatcher.java    License: 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 #27
Source Project: byte-buddy   Author: raphw   File: MethodGraph.java    License: 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 #28
Source Project: byte-buddy   Author: raphw   File: ErasureMatcherTest.java    License: 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 #29
Source Project: byte-buddy   Author: raphw   File: AbstractMethodDescriptionTest.java    License: 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())));
}
 
Example #30
Source Project: activejpa   Author: ActiveJpa   File: ModelClassEnhancer.java    License: 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;
}