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.
You can get only the fields declared in the class with getDeclaredFields. It will exclude inherited fields.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With