【问题标题】:Get the interface name from the implementation class从实现类中获取接口名称
【发布时间】:2013-01-15 11:12:08
【问题描述】:

例子:

List<String> list = new ArrayList<String>();
//This would give me the class name for the list reference variable.
list.getClass().getSimpleName();

我想从list 引用变量中获取接口名称。 有没有办法做到这一点?

【问题讨论】:

    标签: java class interface


    【解决方案1】:

    使用反射,您可以调用 Class.getInterfaces() 方法,该方法返回您的类实现的 Array of Interfaces

    list.getClass().getInterfaces()[0];
    

    只得到名字

    list.getClass().getInterfaces()[0].getSimpleName();
    

    【讨论】:

    • 您可能还想在这些接口扩展的接口上进行递归。
    • @Guillaume 好点,它们将是类实现顺序,例如 interface[0] 将是 java.util.List 而 interface[1] 将是 java.util.RandomAccess
    • 如果你想获得 Collection 接口,你必须在第一次调用返回的接口上调用 getInterface()。
    【解决方案2】:
    Class  aClass = ... //obtain Class object. 
    Class[] interfaces = aClass.getInterfaces();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 2011-01-14
      相关资源
      最近更新 更多