Java Code Examples for net.bytebuddy.description.method.MethodList#size()

The following examples show how to use net.bytebuddy.description.method.MethodList#size() . 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: PropertyAccessorCollector.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 2
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 3
Source File: TransformerInvokerGenerator.java    From Diorite with MIT License 6 votes vote down vote up
@Override
        public ClassVisitor wrap(TypeDescription typeDescription, ClassVisitor cv, Context context, TypePool typePool,
                                 FieldList<FieldDescription.InDefinedShape> fieldList, MethodList<?> methodList, int i, int i1)
        {
//            public void visit(int version, int modifiers, String name, String signature, String superName, String[] interfaces) {
            cv.visit(ClassFileVersion.JAVA_V9.getMinorMajorVersion(), typeDescription.getModifiers(), typeDescription.getInternalName(), null,
                     typeDescription.getSuperClass().asErasure().getInternalName(), typeDescription.getInterfaces().asErasures().toInternalNames());
            TypeDescription clazz = this.clazz;
            String internalName = clazz.getInternalName();
            String descriptor = clazz.getDescriptor();
            MethodList<InDefinedShape> declaredMethods = clazz.getDeclaredMethods();
            int methodsSize = declaredMethods.size();
            String implName = GENERATED_PREFIX + "." + clazz.getName();
            String internalImplName = GENERATED_PREFIX.replace('.', '/') + "/" + internalName;
            String descriptorImplName = "L" + GENERATED_PREFIX.replace('.', '/') + "/" + internalName + ";";

            FieldVisitor fv;
            MethodVisitor mv;
            AnnotationVisitor av0;

            cv.visitEnd();
            return cv;
        }
 
Example 4
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Compiled compile(TypeDescription instrumentedType) {
    FieldDescription fieldDescription = resolve(instrumentedType);
    if (!fieldDescription.getType().asErasure().isVisibleTo(instrumentedType)) {
        throw new IllegalStateException(fieldDescription + " is not visible to " + instrumentedType);
    } else {
        MethodList<?> candidates = methodGraphCompiler.compile(fieldDescription.getType(), instrumentedType)
                .listNodes()
                .asMethodList()
                .filter(matcher);
        List<MethodDelegationBinder.Record> records = new ArrayList<MethodDelegationBinder.Record>(candidates.size());
        MethodDelegationBinder methodDelegationBinder = TargetMethodAnnotationDrivenBinder.of(parameterBinders);
        for (MethodDescription candidate : candidates) {
            records.add(methodDelegationBinder.compile(candidate));
        }
        return new Compiled.ForField(fieldDescription, records);
    }
}
 
Example 5
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Compiled compile(TypeDescription instrumentedType) {
    MethodList<?> targets = new MethodList.Explicit<MethodDescription>(CompoundList.<MethodDescription>of(
            instrumentedType.getDeclaredMethods().filter(isStatic().or(isPrivate())),
            methodGraphCompiler.compile(instrumentedType).listNodes().asMethodList())
    ).filter(named(name).and(takesArguments(0)).and(not(returns(isPrimitive().or(isArray())))));
    if (targets.size() != 1) {
        throw new IllegalStateException(instrumentedType + " does not define method without arguments with name " + name + ": " + targets);
    } else if (!targets.getOnly().getReturnType().asErasure().isVisibleTo(instrumentedType)) {
        throw new IllegalStateException(targets.getOnly() + " is not visible to " + instrumentedType);
    } else {
        MethodList<?> candidates = methodGraphCompiler.compile(targets.getOnly().getReturnType(), instrumentedType)
                .listNodes()
                .asMethodList()
                .filter(matcher);
        List<MethodDelegationBinder.Record> records = new ArrayList<MethodDelegationBinder.Record>(candidates.size());
        MethodDelegationBinder methodDelegationBinder = TargetMethodAnnotationDrivenBinder.of(parameterBinders);
        for (MethodDescription candidate : candidates) {
            records.add(methodDelegationBinder.compile(candidate));
        }
        return new Compiled.ForMethodReturn(targets.get(0), records);
    }
}
 
Example 6
Source File: ConstructorStrategy.java    From byte-buddy with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public MethodRegistry inject(TypeDescription instrumentedType, MethodRegistry methodRegistry) {
    MethodList<?> candidates = instrumentedType.getSuperClass().getDeclaredMethods().filter(isConstructor().and(elementMatcher));
    if (candidates.isEmpty()) {
        throw new IllegalStateException("No possible candidate for super constructor invocation in " + instrumentedType.getSuperClass());
    } else if (!candidates.filter(takesArguments(0)).isEmpty()) {
        candidates = candidates.filter(takesArguments(0));
    } else if (candidates.size() > 1) {
        throw new IllegalStateException("More than one possible super constructor for constructor delegation: " + candidates);
    }
    MethodCall methodCall = MethodCall.invoke(candidates.getOnly());
    for (TypeDescription typeDescription : candidates.getOnly().getParameters().asTypeList().asErasures()) {
        methodCall = methodCall.with(typeDescription.getDefaultValue());
    }
    return methodRegistry.append(new LatentMatcher.Resolved<MethodDescription>(isConstructor().and(takesArguments(0))),
            new MethodRegistry.Handler.ForImplementation(methodCall),
            methodAttributeAppenderFactory,
            Transformer.NoOp.<MethodDescription>make());
}
 
Example 7
Source File: EnhancerImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
static MethodDescription getterOf(FieldDescription persistentField) {
	MethodList<?> methodList = MethodGraph.Compiler.DEFAULT.compile( persistentField.getDeclaringType().asErasure() )
			.listNodes()
			.asMethodList()
			.filter( isGetter(persistentField.getName() ) );
	if ( methodList.size() == 1 ) {
		return methodList.getOnly();
	}
	else {
		return null;
	}
}
 
Example 8
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Precompiles a static method delegation for a given list of methods.
 *
 * @param methods                The methods to consider.
 * @param methodDelegationBinder The method delegation binder to use.
 * @return An appropriate implementation delegate.
 */
protected static ImplementationDelegate of(MethodList<?> methods, MethodDelegationBinder methodDelegationBinder) {
    List<MethodDelegationBinder.Record> records = new ArrayList<MethodDelegationBinder.Record>(methods.size());
    for (MethodDescription methodDescription : methods) {
        records.add(methodDelegationBinder.compile(methodDescription));
    }
    return new ForStaticMethod(records);
}
 
Example 9
Source File: MethodDelegation.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an implementation delegate for constructing a new instance.
 *
 * @param typeDescription        The type being constructed.
 * @param methods                The constructors to consider.
 * @param methodDelegationBinder The method delegation binder to use.
 * @return An appropriate implementation delegate.
 */
protected static ImplementationDelegate of(TypeDescription typeDescription,
                                           MethodList<?> methods,
                                           MethodDelegationBinder methodDelegationBinder) {
    List<MethodDelegationBinder.Record> records = new ArrayList<MethodDelegationBinder.Record>(methods.size());
    for (MethodDescription methodDescription : methods) {
        records.add(methodDelegationBinder.compile(methodDescription));
    }
    return new ForConstruction(typeDescription, records);
}
 
Example 10
Source File: InvokeDynamic.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Creates a lambda expression using the JVM's lambda meta factory. The method that is implementing the lambda expression is provided
 * the explicit arguments first and the functional interface's method second.
 * </p>
 * <p>
 * <b>Important</b>: Byte Buddy does not validate that the provided arguments are correct considering the required arguments of the bound
 * functional interface. Binding an incorrect number of arguments or arguments of incompatible types does not create illegal byte code
 * but yields a runtime error when the call site is first used. This is done to support future extensions or alternative implementations
 * of the Java virtual machine.
 * </p>
 *
 * @param methodDescription   The method that implements the lambda expression.
 * @param functionalInterface The functional interface that is an instance of the lambda expression.
 * @param methodGraphCompiler The method graph compiler to use.
 * @return A builder for creating a lambda expression.
 */
public static WithImplicitArguments lambda(MethodDescription.InDefinedShape methodDescription,
                                           TypeDescription functionalInterface,
                                           MethodGraph.Compiler methodGraphCompiler) {
    if (!functionalInterface.isInterface()) {
        throw new IllegalArgumentException(functionalInterface + " is not an interface type");
    }
    MethodList<?> methods = methodGraphCompiler.compile(functionalInterface)
            .listNodes()
            .asMethodList()
            .filter(isAbstract());
    if (methods.size() != 1) {
        throw new IllegalArgumentException(functionalInterface + " does not define exactly one abstract method: " + methods);
    }
    return bootstrap(new MethodDescription.Latent(new TypeDescription.Latent("java.lang.invoke.LambdaMetafactory",
                    Opcodes.ACC_PUBLIC,
                    TypeDescription.Generic.OBJECT),
                    "metafactory",
                    Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC,
                    Collections.<TypeVariableToken>emptyList(),
                    JavaType.CALL_SITE.getTypeStub().asGenericType(),
                    Arrays.asList(new ParameterDescription.Token(JavaType.METHOD_HANDLES_LOOKUP.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(TypeDescription.STRING.asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_HANDLE.getTypeStub().asGenericType()),
                            new ParameterDescription.Token(JavaType.METHOD_TYPE.getTypeStub().asGenericType())),
                    Collections.<TypeDescription.Generic>emptyList(),
                    Collections.<AnnotationDescription>emptyList(),
                    AnnotationValue.UNDEFINED,
                    TypeDescription.Generic.UNDEFINED),
            JavaConstant.MethodType.of(methods.asDefined().getOnly()),
            JavaConstant.MethodHandle.of(methodDescription),
            JavaConstant.MethodType.of(methods.asDefined().getOnly())).invoke(methods.asDefined().getOnly().getInternalName());
}
 
Example 11
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 12
Source File: SubclassImplementationTarget.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves a special method invocation for a constructor invocation.
 *
 * @param token A token describing the constructor to be invoked.
 * @return A special method invocation for a constructor representing the given method token, if available.
 */
private Implementation.SpecialMethodInvocation invokeConstructor(MethodDescription.SignatureToken token) {
    TypeDescription.Generic superClass = instrumentedType.getSuperClass();
    MethodList<?> candidates = superClass == null
            ? new MethodList.Empty<MethodDescription.InGenericShape>()
            : superClass.getDeclaredMethods().filter(hasSignature(token).and(isVisibleTo(instrumentedType)));
    return candidates.size() == 1
            ? Implementation.SpecialMethodInvocation.Simple.of(candidates.getOnly(), instrumentedType.getSuperClass().asErasure())
            : Implementation.SpecialMethodInvocation.Illegal.INSTANCE;
}