jack_carver
jack_carver

Reputation: 1516

Extracting all fields from java class

I was wondering if there was a easy way to get all defined fields and their types in a given class. This would be easy if the class were to contain only primitive types.

Ex

public class A
{
    int aX;
    String aS;
};

public class B
{
    int bX;
    String bS;
    A aObj;
};

public Class C
{
    boolean bC;
    B bObj;
};

Given C's class I would like extract all fields recursively (aX,aS,bX,bS,bC etc..). Although this isn't particularly difficult to achieve, wanted to know if there are any existing libraries that I could leverage something like the jackson json which I think would have some utility functions which would achieve this.

Thanks

Upvotes: 2

Views: 893

Answers (1)

Jon Egeland
Jon Egeland

Reputation: 12613

The easiest way would be:

public static void run(Class c) {
  for(Field f : c.getFields()) {
    if(!f.getType().isPrimitive())
      System.out.println(f.getName());
    else
      run(f.getType());
  }
}

Using external libraries - especially in Java - is not a good idea if you only use a small part of it. The extra compiling and loading makes your program slower than it needs to be, and takes up too much space to be worth it.

Reference: Java API on Class.

Upvotes: 3

Related Questions