Java Code Examples for net.bytebuddy.description.method.MethodDescription#Token

The following examples show how to use net.bytebuddy.description.method.MethodDescription#Token . 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: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<MethodDescription.Token> extractConstructors(TypeDescription instrumentedType) {
    List<MethodDescription.Token> tokens = doExtractConstructors(instrumentedType), stripped = new ArrayList<MethodDescription.Token>(tokens.size());
    for (MethodDescription.Token token : tokens) {
        stripped.add(new MethodDescription.Token(token.getName(),
                resolveModifier(token.getModifiers()),
                token.getTypeVariableTokens(),
                token.getReturnType(),
                token.getParameterTokens(),
                token.getExceptionTypes(),
                token.getAnnotations(),
                token.getDefaultValue(),
                TypeDescription.Generic.UNDEFINED));
    }
    return stripped;
}
 
Example 2
Source File: InstrumentedType.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public WithFlexibleName withMethod(MethodDescription.Token token) {
    return new Default(name,
            modifiers,
            superClass,
            typeVariables,
            interfaceTypes,
            fieldTokens,
            CompoundList.of(methodTokens, token.accept(Generic.Visitor.Substitutor.ForDetachment.of(this))),
            recordComponentTokens,
            annotationDescriptions,
            typeInitializer,
            loadedTypeInitializer,
            declaringType,
            enclosingMethod,
            enclosingType,
            declaredTypes,
            anonymousClass,
            localClass,
            record,
            nestHost,
            nestMembers);
}
 
Example 3
Source File: ByteBuddy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<MethodDescription.Token> extractConstructors(TypeDescription instrumentedType) {
    List<ParameterDescription.Token> tokens = new ArrayList<ParameterDescription.Token>(instrumentedType.getRecordComponents().size());
    for (RecordComponentDescription.InDefinedShape recordComponent : instrumentedType.getRecordComponents()) {
        tokens.add(new ParameterDescription.Token(recordComponent.getType(),
                recordComponent.getDeclaredAnnotations().filter(targetsElement(ElementType.CONSTRUCTOR))));
    }
    return Collections.singletonList(new MethodDescription.Token(MethodDescription.CONSTRUCTOR_INTERNAL_NAME,
            Opcodes.ACC_PUBLIC,
            Collections.<TypeVariableToken>emptyList(),
            TypeDescription.Generic.VOID,
            tokens,
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            AnnotationValue.UNDEFINED,
            TypeDescription.Generic.UNDEFINED));
}
 
Example 4
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public List<MethodDescription.Token> extractConstructors(TypeDescription instrumentedType) {
    if (instrumentedType.getSuperClass().getDeclaredMethods().filter(isConstructor()).isEmpty()) {
        throw new IllegalStateException("Cannot define default constructor for class without super class constructor");
    }
    return Collections.singletonList(new MethodDescription.Token(Opcodes.ACC_PUBLIC));
}
 
Example 5
Source File: ConstructorStrategyForDefaultConstructorTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings("unchecked")
public void setUp() throws Exception {
    when(methodRegistry.append(any(LatentMatcher.class),
            any(MethodRegistry.Handler.class),
            any(MethodAttributeAppender.Factory.class),
            any(Transformer.class))).thenReturn(methodRegistry);
    when(instrumentedType.getSuperClass()).thenReturn(superClass);
    when(superClass.getDeclaredMethods()).thenReturn(new MethodList.Explicit<MethodDescription.InGenericShape>(methodDescription));
    when(methodDescription.isConstructor()).thenReturn(true);
    when(methodDescription.isVisibleTo(instrumentedType)).thenReturn(true);
    when(methodDescription.asToken(ElementMatchers.is(instrumentedType))).thenReturn(token);
    when(token.getName()).thenReturn(FOO);
    when(token.getModifiers()).thenReturn(MODIFIERS);
    when(token.getTypeVariableTokens()).thenReturn(new ByteCodeElement.Token.TokenList<TypeVariableToken>());
    when(token.getReturnType()).thenReturn(typeDescription);
    when(token.getParameterTokens()).thenReturn(new ByteCodeElement.Token.TokenList<ParameterDescription.Token>());
    when(token.getExceptionTypes()).thenReturn(new TypeList.Generic.Empty());
    when(token.getAnnotations()).thenReturn(new AnnotationList.Empty());
    when(token.getDefaultValue()).thenReturn((AnnotationValue) defaultValue);
    when(token.getReceiverType()).thenReturn(typeDescription);
    stripped = new MethodDescription.Token(FOO,
            MODIFIERS,
            Collections.<TypeVariableToken>emptyList(),
            typeDescription,
            Collections.<ParameterDescription.Token>emptyList(),
            Collections.<TypeDescription.Generic>emptyList(),
            Collections.<AnnotationDescription>emptyList(),
            defaultValue,
            TypeDescription.Generic.UNDEFINED);
}
 
Example 6
Source File: Transformer.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodDescription.Token transform(TypeDescription instrumentedType, MethodDescription.Token target) {
    return new MethodDescription.Token(target.getName(),
            resolver.resolve(target.getModifiers()),
            target.getTypeVariableTokens(),
            target.getReturnType(),
            target.getParameterTokens(),
            target.getExceptionTypes(),
            target.getAnnotations(),
            target.getDefaultValue(),
            target.getReceiverType());
}
 
Example 7
Source File: MethodRegistryDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testVisibilityBridgeIfNotMatchedAndVisible() throws Exception {
    when(instrumentedMethod.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(parameterDescription.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty());
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    when(firstFilter.matches(instrumentedMethod)).thenReturn(false);
    when(secondFilter.matches(instrumentedMethod)).thenReturn(false);
    when(resolvedMethodFilter.matches(instrumentedMethod)).thenReturn(true);
    TypeDescription declaringType = mock(TypeDescription.class);
    when(declaringType.asErasure()).thenReturn(declaringType);
    when(instrumentedMethod.getDeclaringType()).thenReturn(declaringType);
    when(thirdType.isPublic()).thenReturn(true);
    when(instrumentedMethod.isPublic()).thenReturn(true);
    when(declaringType.isPackagePrivate()).thenReturn(true);
    TypeDescription.Generic superClass = mock(TypeDescription.Generic.class);
    TypeDescription rawSuperClass = mock(TypeDescription.class);
    when(superClass.asErasure()).thenReturn(rawSuperClass);
    when(typeDescription.getSuperClass()).thenReturn(superClass);
    MethodDescription.Token methodToken = mock(MethodDescription.Token.class);
    when(instrumentedMethod.asToken(ElementMatchers.is(typeDescription))).thenReturn(methodToken);
    when(methodToken.accept(any(TypeDescription.Generic.Visitor.class))).thenReturn(methodToken);
    when(classFileVersion.isAtLeast(ClassFileVersion.JAVA_V5)).thenReturn(true);
    MethodRegistry.Compiled methodRegistry = new MethodRegistry.Default()
            .append(firstMatcher, firstHandler, firstFactory, transformer)
            .append(secondMatcher, secondHandler, secondFactory, transformer)
            .prepare(firstType, methodGraphCompiler, TypeValidation.ENABLED, VisibilityBridgeStrategy.Default.ALWAYS, methodFilter)
            .compile(implementationTargetFactory, classFileVersion);
    assertThat(methodRegistry.getInstrumentedType(), is(typeDescription));
    assertThat(methodRegistry.getInstrumentedMethods().size(), is(1));
    assertThat(methodRegistry.getTypeInitializer(), is(typeInitializer));
    assertThat(methodRegistry.getLoadedTypeInitializer(), is(loadedTypeInitializer));
    verify(firstHandler).prepare(firstType);
    verify(secondHandler).prepare(secondType);
    verifyZeroInteractions(firstFactory);
    verifyZeroInteractions(secondFactory);
    assertThat(methodRegistry.target(instrumentedMethod), instanceOf(TypeWriter.MethodPool.Record.ForDefinedMethod.OfVisibilityBridge.class));
}
 
Example 8
Source File: SubclassDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Applies this builder's constructor strategy to the given instrumented type.
 *
 * @param instrumentedType The instrumented type to apply the constructor onto.
 * @return The instrumented type with the constructor strategy applied onto.
 */
private InstrumentedType applyConstructorStrategy(InstrumentedType instrumentedType) {
    if (!instrumentedType.isInterface()) {
        for (MethodDescription.Token token : constructorStrategy.extractConstructors(instrumentedType)) {
            instrumentedType = instrumentedType.withMethod(token);
        }
    }
    return instrumentedType;
}
 
Example 9
Source File: TransformerForMethodTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testModifierTransformation() throws Exception {
    MethodDescription.Token transformed = new Transformer.ForMethod.MethodModifierTransformer(ModifierContributor.Resolver.of(modifierContributor))
            .transform(instrumentedType, methodToken);
    assertThat(transformed.getName(), is(FOO));
    assertThat(transformed.getModifiers(), is((MODIFIERS & ~RANGE) | MASK));
    assertThat(transformed.getReturnType(), is(returnType));
    assertThat(transformed.getTypeVariableTokens().size(), is(1));
    assertThat(transformed.getTypeVariableTokens().get(0), is(new TypeVariableToken(QUX, Collections.singletonList(typeVariableBound))));
    assertThat(transformed.getExceptionTypes().size(), is(1));
    assertThat(transformed.getExceptionTypes().getOnly(), is(exceptionType));
    assertThat(transformed.getParameterTokens().size(), is(1));
    assertThat(transformed.getParameterTokens().getOnly(), is(parameterToken));
}
 
Example 10
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Override
protected List<MethodDescription.Token> doExtractConstructors(TypeDescription instrumentedType) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    MethodList<?> defaultConstructors = superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(isConstructor().and(takesArguments(0)).<MethodDescription>and(isVisibleTo(instrumentedType)));
    if (defaultConstructors.size() == 1) {
        return Collections.singletonList(new MethodDescription.Token(Opcodes.ACC_PUBLIC));
    } else {
        throw new IllegalArgumentException(instrumentedType.getSuperClass() + " declares no constructor that is visible to " + instrumentedType);
    }
}
 
Example 11
Source File: InstrumentedTypeDefaultTest.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodTokenIsVisited() throws Exception {
    MethodDescription.Token token = mock(MethodDescription.Token.class);
    InstrumentedType instrumentedType = makePlainInstrumentedType();
    assertThat(instrumentedType.withMethod(token), is(instrumentedType));
    verify(token).accept(matchesPrototype(TypeDescription.Generic.Visitor.Substitutor.ForDetachment.of(instrumentedType)));
    verifyNoMoreInteractions(token);
}
 
Example 12
Source File: InstrumentedType.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public WithFlexibleName withMethod(MethodDescription.Token token) {
    throw new IllegalStateException("Cannot define method for frozen type: " + typeDescription);
}
 
Example 13
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Extracts constructors for a given super type. The extracted constructor signatures will then be imitated by the
 * created dynamic type.
 *
 * @param instrumentedType The type for which the constructors should be created.
 * @return A list of tokens that describe the constructors that are to be implemented.
 */
List<MethodDescription.Token> extractConstructors(TypeDescription instrumentedType);
 
Example 14
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Extracts the relevant method tokens of the instrumented type's constructors.
 *
 * @param instrumentedType The type for which to extract the constructors.
 * @return A list of relevant method tokens.
 */
protected abstract List<MethodDescription.Token> doExtractConstructors(TypeDescription instrumentedType);
 
Example 15
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
@Override
protected List<MethodDescription.Token> doExtractConstructors(TypeDescription instrumentedType) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    return (superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(isConstructor().and(isVisibleTo(instrumentedType)))).asTokenList(is(instrumentedType));
}
 
Example 16
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
@Override
protected List<MethodDescription.Token> doExtractConstructors(TypeDescription instrumentedType) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    return (superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(isConstructor().and(isVisibleTo(instrumentedType)))).asTokenList(is(instrumentedType));
}
 
Example 17
Source File: RebaseDynamicTypeBuilder.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a matcher that filters any method that should not be rebased.
 *
 * @param instrumentedType    The instrumented type.
 * @param instrumentedMethods All instrumented methods.
 * @return A suitable matcher that filters all methods that should not be rebased.
 */
protected static ElementMatcher<MethodDescription.Token> of(TypeDescription instrumentedType, MethodList<?> instrumentedMethods) {
    return new RebaseableMatcher(new HashSet<MethodDescription.Token>(instrumentedMethods.asTokenList(is(instrumentedType))));
}
 
Example 18
Source File: InstrumentedType.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * {@inheritDoc}
 */
WithFlexibleName withMethod(MethodDescription.Token token);
 
Example 19
Source File: Transformer.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new transforming method transformer.
 *
 * @param transformer The transformer to be applied.
 */
public ForMethod(Transformer<MethodDescription.Token> transformer) {
    this.transformer = transformer;
}
 
Example 20
Source File: LatentMatcher.java    From byte-buddy with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new latent matcher for a method token.
 *
 * @param token A token representing the method being matched.
 */
public ForMethodToken(MethodDescription.Token token) {
    this.token = token;
}