Wednesday, 19 July 2017

Java | getFields vs getDeclaredFields in Java Reflection

getFields() method:
If this Class object represents a class, this method returns the public fields of this class and of all its superclasses. If this Class object represents an interface, this method returns the fields of this interface and of all its superinterfaces.

getDeclaredFields() method:
Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.
All the fields, regardless of their accessibility but only for the current class, not any base classes that the current class might be inheriting from.

package com.java.reflection;
import java.lang.reflect.Field;
class Parent {
     private String privateParentVar;
     public String publicParentVar;
}

class Child extends Parent {
     private String privateChildVar;
     public String publicChildVar;
}


public class TestReflection {
    
     public static void main(String[] args) {
           Field[] decFields =Child.class.getDeclaredFields();
           printArray("getDeclaredFields",decFields);

           Field[] fields =Child.class.getFields();
           printArray("getFields",fields);
     }

     private static void printArray(String method,Field[] decFields) {
           System.out.print("\n"+method+":");
           for (Field field : decFields) {
                System.out.print(field.getName()+" ");
           }
     }
}

Output:
getDeclaredFields:privateChildVar publicChildVar
getFields:publicChildVar publicParentVar


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...