FunctionalInterfaceLogic.java

/*
 * Copyright (C) 2015-2016 Federico Tomassetti
 * Copyright (C) 2017-2026 The JavaParser Team.
 *
 * This file is part of JavaParser.
 *
 * JavaParser can be used either under the terms of
 * a) the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * b) the terms of the Apache License
 *
 * You should have received a copy of both licenses in LICENCE.LGPL and
 * LICENCE.APACHE. Please refer to those files for details.
 *
 * JavaParser is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 */
package com.github.javaparser.resolution.logic;

import com.github.javaparser.resolution.MethodUsage;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import com.github.javaparser.resolution.types.ResolvedType;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Federico Tomassetti
 */
public final class FunctionalInterfaceLogic {

    private static String JAVA_LANG_FUNCTIONAL_INTERFACE = FunctionalInterface.class.getCanonicalName();

    private FunctionalInterfaceLogic() {
        // prevent instantiation
    }

    /**
     * Get the functional method defined by the type, if any.
     *
     * <p>Per JLS ��9.8, a functional interface is always an <em>interface</em>, which is a reference
     * type. Primitive types, array types, and void can therefore never be functional interfaces.
     * Passing such a type returns {@link Optional#empty()} immediately without throwing an exception.
     *
     * <p>Note: bounded type variables ({@code <T extends Runnable>}) and intersection types
     * ({@code Runnable & Serializable}) are not handled here and also return {@link Optional#empty()}.
     * Supporting those cases is a separate, more complex enhancement (see JLS ��15.27.3).
     *
     * @param type the resolved type to inspect ��� may be any {@link ResolvedType} subclass
     * @return the single abstract method of the functional interface, or empty if the type is not
     *     a functional interface or is not a reference type at all
     * @see <a href="https://github.com/javaparser/javaparser/issues/3625">Issue #3625</a>
     */
    public static Optional<MethodUsage> getFunctionalMethod(ResolvedType type) {
        // Guard added to fix issue #3625:
        // asReferenceType() throws UnsupportedOperationException on non-reference types
        // (e.g. ResolvedArrayType, ResolvedPrimitiveType). Since a functional interface is by
        // definition an interface ��� a reference type ��� returning empty() here is both safe
        // and semantically correct.
        if (!type.isReferenceType()) {
            return Optional.empty();
        }
        Optional<ResolvedReferenceTypeDeclaration> optionalTypeDeclaration =
                type.asReferenceType().getTypeDeclaration();
        if (!optionalTypeDeclaration.isPresent()) {
            return Optional.empty();
        }
        ResolvedReferenceTypeDeclaration typeDeclaration = optionalTypeDeclaration.get();
        if (typeDeclaration.isInterface()) {
            return getFunctionalMethod(typeDeclaration);
        }
        return Optional.empty();
    }

    /**
     * Get the functional method defined by the type, if any.
     */
    public static Optional<MethodUsage> getFunctionalMethod(ResolvedReferenceTypeDeclaration typeDeclaration) {
        // We need to find all abstract methods
        // Remove methods inherited by Object:
        Set<MethodUsage> // Remove methods inherited by Object:
                // Consider the case of Comparator which define equals. It would be considered a functional method.
                methods = typeDeclaration.getAllMethods().stream()
                        .filter(m -> m.getDeclaration().isAbstract())
                        .filter(m -> !isPublicMemberOfObject(m))
                        .collect(Collectors.toSet());
        // TODO a functional interface can have multiple subsignature method with a return-type-substitutable
        // see https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8
        if (methods.size() == 0) {
            return Optional.empty();
        }
        Iterator<MethodUsage> iterator = methods.iterator();
        MethodUsage methodUsage = iterator.next();
        while (iterator.hasNext()) {
            MethodUsage otherMethodUsage = iterator.next();
            if (!(methodUsage.isSameSignature(otherMethodUsage)
                    || methodUsage.isSubSignature(otherMethodUsage)
                    || otherMethodUsage.isSubSignature(methodUsage))) {
                methodUsage = null;
                break;
            }
            if (!(methodUsage.isReturnTypeSubstituable(otherMethodUsage))) {
                methodUsage = null;
                break;
            }
        }
        return Optional.ofNullable(methodUsage);
    }

    public static boolean isFunctionalInterfaceType(ResolvedType type) {
        if (type.isReferenceType()) {
            Optional<ResolvedReferenceTypeDeclaration> optionalTypeDeclaration =
                    type.asReferenceType().getTypeDeclaration();
            if (optionalTypeDeclaration.isPresent()
                    && optionalTypeDeclaration.get().hasAnnotation(JAVA_LANG_FUNCTIONAL_INTERFACE)) {
                return true;
            }
        }
        return getFunctionalMethod(type).isPresent();
    }

    private static String getSignature(Method m) {
        return String.format(
                "%s(%s)",
                m.getName(),
                String.join(
                        ", ",
                        Arrays.stream(m.getParameters())
                                .map(p -> toSignature(p))
                                .collect(Collectors.toList())));
    }

    private static String toSignature(Parameter p) {
        return p.getType().getCanonicalName();
    }

    private static List<String> OBJECT_PUBLIC_METHODS_SIGNATURES = Arrays.stream(Object.class.getDeclaredMethods())
            .filter(m -> Modifier.isPublic(m.getModifiers()))
            .map(method -> getSignature(method))
            .collect(Collectors.toList());

    private static boolean isPublicMemberOfObject(MethodUsage m) {
        return OBJECT_PUBLIC_METHODS_SIGNATURES.contains(m.getDeclaration().getSignature());
    }
}