How can I find java code base for interfaces that have one method?

The project I'm working on has recently switched from Java 7 to Java 8. I would like to be able to find interfaces that have one abstract method as candidates for introducing functional interfaces into our code base. ( @FunctionalInterface existing interfaces like @FunctionalInterface , extending them from interfaces to java.util.function or maybe just replacing them).

+5
source share
1 answer

The reflections project is able to find and return all classes in the classpath. Here is a working example:

 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); 

The isObjectMethod is defined as follows:

 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())); } 

This will not help you return to the source code and add annotations, but it will give you a list for work.

+6
source

Source: https://habr.com/ru/post/1240205/


All Articles