首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在java代码库中搜索具有单个方法的接口?

如何在java代码库中搜索具有单个方法的接口?
EN

Stack Overflow用户
提问于 2016-01-08 23:03:23
回答 1查看 276关注 0票数 5

最近,我从事的一个项目已经从Java 7转向了Java 8,我希望能够找到具有单一抽象方法的接口,作为将函数接口引入我们的代码库的候选。(将现有接口注释为@FunctionalInterface,从java.util.function中的接口扩展它们,或者可能只是替换它们)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-08 23:21:11

倒影项目能够定位并返回类路径上的所有类。下面是一个有用的例子:

代码语言:javascript
复制
ReflectionUtils.forNames(new Reflections(new ConfigurationBuilder().setScanners(new SubTypesScanner(false))
                                                                   .addUrls(ClasspathHelper.forClassLoader()))
                         .getAllTypes()).stream()
               .filter(Class::isInterface)
               .collect(toMap(c -> c,
                              c -> Arrays.stream(c.getMethods())
                                         .filter(m -> !m.isDefault())
                                         .filter(m -> !Modifier.isStatic(m.getModifiers()))
                                         .filter(m -> !isObjectMethod(m))
                                         .collect(toSet())))
               .entrySet().stream()
               .filter(e -> e.getValue().size() == 1)
               .sorted(comparing(e -> e.getKey().toString()))
               .map(e -> e.getKey().toString() + " has single method " + e.getValue())//getOnlyElement(e.getValue()))
               .forEachOrdered(System.out::println);

isObjectMethod助手的定义如下:

代码语言:javascript
复制
private static final Set<Method> OBJECT_METHODS = ImmutableSet.copyOf(Object.class.getMethods());
private static boolean isObjectMethod(Method m){
    return OBJECT_METHODS.stream()
                         .anyMatch(om -> m.getName().equals(om.getName()) &&
                                         m.getReturnType().equals(om.getReturnType()) &&
                                         Arrays.equals(m.getParameterTypes(),
                                                       om.getParameterTypes()));
}

这并不能帮助您返回源代码并添加注释,但它将为您提供一个可供使用的列表。

按照意见中的要求,开展这项工作所需的进口如下:

代码语言:javascript
复制
import static java.util.Comparator.*;
import static java.util.stream.Collectors.*;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Set;

import org.reflections.ReflectionUtils;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import com.google.common.collect.ImmutableSet;
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34687533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档