Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Reflection: Get fields belonging to current class only

How can I get the fields associated only with the current class instead of all of its parent classes as well?

public class BaseClass()
{
     public int x = 0;
}

public class AnotherClass() extends BaseClass
{
     public int y = -1;
     public int z = -2;

     public void doStuff()
     {
          for(Field f : this.getClass().getFields())
          {
              //Save each field to a file
          }
     }
}

I want to get only Y and Z, which belong to AnotherClass. But the above gives me X as well.

This is meant to replace having to type each value that I want to save. It's not being saved in any typical format. It must be saved like this so don't suggest saving the fields in a different way.

Filtering out each field's name would defeat the purpose of this as there are well over 200.

like image 383
WildBamaBoy Avatar asked Apr 14 '26 23:04

WildBamaBoy


2 Answers

You can get only the fields declared in the class with getDeclaredFields. It will exclude inherited fields.

like image 50
Patrick Avatar answered Apr 16 '26 14:04

Patrick


You can filter based upon the Field's getDeclaredClass():

public static List<Field> fieldsDeclaredDirectlyIn(Class<?> c) {
    final List<Field> l = new ArrayList<Field>();
    for (Field f : c.getFields())
        if (f.getDeclaringClass().equals(c))
            l.add(f);
    return l;
}

This picks just y and z for your example.

like image 44
FauxFaux Avatar answered Apr 16 '26 12:04

FauxFaux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!