查找类集合中最接近的公共超类(或超接口)

查找类集合中最接近的公共超类(或超接口),第1张

查找类集合中最接近的公共超类(或超接口)

据我所知,完整的解决方案

  • 每个类层次结构的BFS都是“向上”的-生成linkedHashSet(保留顺序+无重复)
  • 将每个集合与下一个相交以找到任何共同点,再次使用linkedHashSet保留顺序
  • 其余的“有序”集合是共同祖先,列表中的第一个是“最近的”,最后一个是最远的。
  • 空列表意味着没有祖先(对象除外)

private static Set<Class<?>> getClassesBfs(Class<?> clazz) {    Set<Class<?>> classes = new linkedHashSet<Class<?>>();    Set<Class<?>> nextLevel = new linkedHashSet<Class<?>>();    nextLevel.add(clazz);    do {        classes.addAll(nextLevel);        Set<Class<?>> thisLevel = new linkedHashSet<Class<?>>(nextLevel);        nextLevel.clear();        for (Class<?> each : thisLevel) { Class<?> superClass = each.getSuperclass(); if (superClass != null && superClass != Object.class) {     nextLevel.add(superClass); } for (Class<?> eachInt : each.getInterfaces()) {     nextLevel.add(eachInt); }        }    } while (!nextLevel.isEmpty());    return classes;}private static List<Class<?>> commonSuperClass(Class<?>... classes) {    // start off with set from first hierarchy    Set<Class<?>> rollingIntersect = new linkedHashSet<Class<?>>( getClassesBfs(classes[0]));    // intersect with next    for (int i = 1; i < classes.length; i++) {        rollingIntersect.retainAll(getClassesBfs(classes[i]));    }    return new linkedList<Class<?>>(rollingIntersect);}

配套方法及试验

private static void test(Class<?>... classes) {    System.out.println("Common ancestor for " + simpleClassList(Arrays.asList(classes)) + ", Result =>  " + simpleClassList(commonSuperClass(classes)));}private static String simpleClassList(Collection<Class<?>> classes) {    StringBuilder builder = new StringBuilder();    for (Class<?> clazz : classes) {        builder.append(clazz.getSimpleName());        builder.append(",");    }    return builder.toString();}public static void main(String[] args) {    test(A.class, AImpl.class);    test(A.class, B.class, C.class);    test(A.class, AB.class);    test(AImpl.class, ABImpl.class);    test(ABImpl.class, ABImpl2.class);    test(AImpl.class, ABImpl.class, ABImpl2.class);    test(ABImpl.class, ABImpl2.class, BCImpl.class);    test(AImpl.class, ABImpl.class, ABImpl2.class, BCImpl.class);    test(AB.class, ABImpl.class);}

输出量

Common ancestor for A,AImpl,, Result =>  A,Common ancestor for A,B,C,, Result =>  Common ancestor for A,AB,, Result =>  A,Common ancestor for AImpl,ABImpl,, Result =>  A,Common ancestor for ABImpl,ABImpl2,, Result =>  A,B,Common ancestor for AImpl,ABImpl,ABImpl2,, Result =>  A,Common ancestor for ABImpl,ABImpl2,BCImpl,, Result =>  B,Common ancestor for AImpl,ABImpl,ABImpl2,BCImpl,, Result =>  Common ancestor for AB,ABImpl,, Result =>  AB,A,B,


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5091877.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存