【问题标题】:Getting SuperInterfaces in java在java中获取超级接口
【发布时间】:2012-04-10 12:32:09
【问题描述】:

我已经尝试这样做很长时间了,但似乎无法获得所需的输出。

我想做的是有一个类名说java.util.Vector

得到:

  • java.util.Vector 直接实现的接口。
  • 由超类直接实现的接口。
  • 以及这些接口的所有超级接口。

任何帮助将不胜感激。

【问题讨论】:

  • 您在寻找 java.lang.Class 方法吗?获取接口?
  • 是的,我使用 getInterfaces();我为此使用递归还是有其他方法?
  • 我会使用递归。周围有很多样本,例如java2s.com/Tutorial/Java/0125__Reflection/…

标签: java class interface


【解决方案1】:

您可以使用reflection 来创建BFS

从仅包含VectorSet<Class<?>> 开始,并使用Class.getInterfaces()Class.getSuperclass() 迭代地增加新元素的集合

将刚刚添加的元素添加到Queue [BFS 运行所需的]。队列为空时终止。

后处理:迭代 Set - 并且只获取使用 Class.isInterface() 的接口对象

应该是这样的:

Class<?> cl = Vector.class;
Queue<Class<?>> queue = new LinkedList<Class<?>>();
Set<Class<?>> types =new HashSet<Class<?>>();
queue.add(cl);
types.add(cl);
    //BFS:
while (queue.isEmpty() == false) {
    Class<?> curr = queue.poll();
    Class<?>[] supers = curr.getInterfaces();
    for (Class<?> next : supers) {
        if (next != null && types.contains(next) == false) {
            types.add(next);
            queue.add(next);
        }
    }
    Class<?> next = curr.getSuperclass();
    if (next != null && types.contains(next) == false) {
        queue.add(next);
        types.add(next);
    }
}
    //post processing:
for (Class<?> curr : types) { 
    if (curr.isInterface()) System.out.println(curr);
}

【讨论】:

    【解决方案2】:

    虽然 java.util.Vector 不是接口,因此您不能使用接口对其进行扩展,但您可以使用 Reflections 之类的库来容纳这些功能。 Reflections 允许您扫描类路径并查询一组条件,例如实现或扩展给定类/接口的条件。我已经在几个需要扫描接口实现和带注释的类的项目中成功使用它。

    这是明确的链接:http://code.google.com/p/reflections/

    此外,如果您只想找出类扩展/实现的类/接口,您可以通过类属性使用类反射 API。

    这里有一些例子:

    //get all public methods of Vector
    Vector.class.getMethods();
    //get all methods of the superclass (AbstractList) of Vector
    Vector.class.getSuperclass().getMethods();
    //get all interfaces implemented by Vector
    Vector.class.getInterfaces();
    

    【讨论】:

      【解决方案3】:

      如果您愿意使用其他库:使用apache-commons-lang

      【讨论】:

      • 您提供的链接已失效。请考虑删除帖子或更新链接。谢谢!
      【解决方案4】:

      来自Apache Commons LangClassUtils.getAllInterfaces 方法将执行此操作:

      List<Class<?>> supernterfaces = ClassUtils.getAllInterfaces(java.util.Vector.class);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-24
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 2013-04-14
        • 2018-12-26
        • 2014-02-23
        • 1970-01-01
        相关资源
        最近更新 更多