Java

Java Reflection: Class.getFields() and Class.getDeclaredFields()


Reflection in Java is not something used regularly in software development unless you work with frameworks or development tools etc. A few days back I was working on a piece of code which required me to fetch all the field/property objects that was contained in a POJO (Plain Old Java Object) whose class name was given.

To get at the fields contained in a java object first you need to create a ‘Class’ instance of the class in question. Then you can use either Class.getFields() or Class.getDelcaredFields() to get an array of fields.

The difference between Class.getFields() and Class.getDelcaredFields() is that the first method includes fields inherited from it’s parent class (if it has one) while the second method only returns fields declared in the specified class.

The code below shows this difference where Shape is an abstract class extended by Circle and Square.

package reflectionexample;

import java.lang.reflect.Field;

abstract class Shape {

    int numberOfSides;

    protected abstract double calculateArea();

    public final int getNumberOfSides() {
        return numberOfSides;
    }
}

class Circle extends Shape{
    int radius;
    public Circle(int radius) {
        this.radius = radius;
    }    
       
    @Override
    protected double calculateArea() {
        return Math.PI * radius * radius;
    }
}

class Square extends Shape {
    int sideLength;
    Square() {
        numberOfSides = 4;
    }

    public void setSideLength(int sideL) {
        sideLength = sideL;
    }

    @Override
    protected double calculateArea() {
        return this.sideLength * this.sideLength;
    }
}

public class ReflectionExample {

       public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {        
                
        Class squareClass = Class.forName("reflectionexample.Square");
        
        Field[] fields = squareClass.getDeclaredFields(); //does not include fields declared in Shape
        for (Field f : fields) {
            System.out.println("field name = " + f.getName()); //prints only 'sideLength'           
        }
        
        Class circleClass = Class.forName("reflectionexample.Circle");
        fields = circleClass.getFields(); //includes fields declared in the Shape abstract class
        for (Field f : fields) {
            System.out.println("field name = " + f.getName()); //prints 'numberOfSides' and 'radius'
        }        
    }
}

There are more interesting stuff when it comes to using reflection to get fields of a class. One important feature is the ability to access private fields. More on this on a future blog.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s