最近,我从事的一个项目已经从Java 7转向了Java 8,我希望能够找到具有单一抽象方法的接口,作为将函数接口引入我们的代码库的候选。(将现有接口注释为@FunctionalInterface,从java.util.function中的接口扩展它们,或者可能只是替换它们)。
发布于 2016-01-08 23:21:11
倒影项目能够定位并返回类路径上的所有类。下面是一个有用的例子:
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助手的定义如下:
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()));
}这并不能帮助您返回源代码并添加注释,但它将为您提供一个可供使用的列表。
按照意见中的要求,开展这项工作所需的进口如下:
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;https://stackoverflow.com/questions/34687533
复制相似问题