使用反射确定字段是否是我创建的类型

时间:2014-12-19 08:41:34

标签: java reflection

假设我有一个对象,我把它带到了字段:

Field[] fields = obj.getFields();

现在我正在迭代每一个并且想要打印它们的成员,如果它是某种类,否则只要使用field.get(obj)以防它是一个字符串,int或该命令将打印其值的任何内容,不只是参考指针。

我如何检测它?

5 个答案:

答案 0 :(得分:1)

您可以在不需要实例化的情况下获得类的每个字段的Type

public class GetFieldType {

    public static void main (String [] args) {
        Field [] fields = Hello.class.getFields();

        for (Field field: fields) {
            System.out.println(field.getGenericType());
        }
    }

    public static class Hello {
        public ByeBye bye;
        public String message;
        public Integer b;
        ...
    }
}

答案 1 :(得分:0)

您可以使用instanceof分隔对象。

public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    Object[] objects = new Object[4];
    objects[0] = new Integer(2);
    objects[1] = "StringTest";
    objects[2] = new BigDecimal(2.00d);
    for (Object obj : objects) {
        if (obj != null) {
            if (obj instanceof BigDecimal) {
                System.out.println("bigdecimal found " + obj);
            } else if (obj instanceof String) {
                System.out.println("String found " + obj);
            } else {
                System.out.println("Integer found " + obj);
            }
        }
        else{
            System.out.println("object is null");
        }
    }
}

答案 2 :(得分:0)

如果您需要测试对象是否来自您的项目,您可以查看包名称并将其与项目的包名称进行比较。

您可以对声明的字段类型或字段内容的运行时类型执行此操作。下面的代码段演示了后一种方法:

SomeClass foo = new SomeClass();

for (Field f : foo.getClass().getDeclaredFields()) {

  boolean wasAccessible = f.isAccessible();
  try {
    f.setAccessible(true);
    Object object = f.get(foo);

    if (object != null) {

      if (object.getClass().getPackage().getName()
          .startsWith("your.project.package")) {
        // one of yours
      }
    } else {
      // handle a null value
    }
  } finally {
    f.setAccessible(wasAccessible);
  }
}

请记住obj.getFields();仅返回可公开访问的字段。你可能想要考虑getDeclaredFields(),就像我上面所做的那样。如果您坚持使用getFields(),则可以省略上述示例中的辅助功能代码。

答案 3 :(得分:0)

通过一些工作,您可以通过加载它们的类加载器来区分您的类。看看这个:

Find where java class is loaded from

虽然这可能有所帮助,但它不会成为你问题的灵丹妙药,主要是因为:

  • primitives(byte,short,char,int,long,float,double和boolean)不是类。
  • 类加载器的体系结构在不同的应用服务器中是不同的。
  • 不同的类加载器可以多次加载同一个类。

答案 4 :(得分:0)

我理解的是你在对象层次结构中递归并得到基元的值

public class ParentMostClass {
   int a = 5;
   OtherClass other = new OtherClass();

   public static void main(String[] args) throws IllegalArgumentException,
    IllegalAccessException {
      ParentMostClass ref = new ParentMostClass();
      printFiledValues(ref);
  }

public static void printFiledValues(Object obj)
    throws IllegalArgumentException, IllegalAccessException {

    Class<? extends Object> calzz = obj.getClass();
    Field[] fileds = obj.getClass().getDeclaredFields();

    for (Field field : fileds) {
        Object member = field.get(obj);
        // you need to handle all primitive, they are few
        if (member instanceof String || member instanceof Number) {
            System.out.println(calzz + "->" + field.getName() + " : "
            + member);
        } else {
           printFiledValues(member);
    }
  }
}
}

public class OtherClass {
    int b=10;
}

我的输出为

class com.example.ParentMostClass->a : 5
class com.example.OtherClass->b : 10
相关问题