如何以编程方式读取Java接口



我想实现一个从定义指定(int)值的接口返回字段的方法。我没有接口的源代码。

所以,签名可以是这样的:
public ArrayList<String> getFieldnames(Object src, int targetValue);

我假设它可以在内部找到声明的字段,并根据值测试每个字段,返回列表。

ArrayList<String> s = new ArrayList<String>();
if( src!= null )
{
    Field[] flist = src.getClass().getDeclaredFields();
    for (Field f : flist )
        if( f.getType() == int.class )
            try {
                if( f.getInt(null) == targetValue) {
                    s.add(f.getName());
                    break;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            }
}
return s;

不幸的是,这个实现是不正确的——就好像用接口本身调用时根本没有字段一样。如果我传递一个实现接口的对象,可能的字段列表将太宽而无法使用。

谢谢你的帮助!

public ArrayList<String> getFieldnames(Object src, int targetValue) {
  final Class<?> myInterfaceClass = MyInterface.class;
  ArrayList<String> fieldNames = new ArrayList<>();
  if (src != null) {
    for (Class<?> currentClass = src.getClass(); currentClass != null; currentClass = currentClass.getSuperclass()) {
      Class<?> [] interfaces = currentClass.getInterfaces();
      if (Arrays.asList(interfaces).contains(myInterfaceClass)) {
        for (Field field : currentClass.getDeclaredFields()) {
          if (field.getType().equals(int.class)) {
            try {
              int value = field.getInt(null);
              if (value == targetValue) {
                fieldNames.add(field.getName());
              }
            } catch (IllegalAccessException ex) {
              // Do nothing. Always comment empty blocks.
            }
          }
        }
      }
    }
  }
  return fieldNames;
}

This

src.getClass()

返回SRC类而不是接口。考虑这个

interface I {
}
class A implements I {
}
new A().getClass() -- returns A.class 

虽然我宁愿传入一个对象,但我认为将签名更改为字符串值并传入FQIN也可以很好地完成工作。

感谢<这个问题>的想法(和谷歌引导我到那里)。

解决方案:

public ArrayList<String> getFieldnamesByValue(Class<?>x, int targetValue)
{
    ArrayList<String> s = new ArrayList<String>();
    if( x != null )
    {
        Field[] flist = x.getDeclaredFields();
        for (Field f : flist )
            if( f.getType() == int.class )
                try {
                    if( f.getInt(null) == targetValue) {
                        s.add(f.getName());
                        break;
                    }
                } catch (IllegalArgumentException e) {
                } catch (IllegalAccessException e) {
                }
    }
    return s;
}

最新更新