Over a million developers have joined DZone.

Reflection - Get Vs GetDeclared Methods

·
The below code demonstrates the difference between getX and getDeclaredX (getMethods/getDeclaredMethods, getFields/getDeclaredFields etc)

Here is the code for MyObject class:

package com.test.reflection;

public class MyObject1 {

	public int i;
	protected int j;
	private int k;
	
	public MyObject1(){
		System.out.println("No-arg constructor called!!");
	}
	
	public MyObject1(int i){
		System.out.println("1-arg constructor called!!");
	}
	
	private MyObject1(String str){
		System.out.println("1-arg private constructor called!!");
	}
	
	public void method1(){
		System.out.println("Inside method1");
	}
	
	public int method2(int i){
		System.out.println("Inside method2");
		return i;
	}
	
}


Here is the code for main method:

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class Reflection1 {

	public static void main(String[] args) throws Exception {
		
		Class classObj = MyObject1.class;

		Field[] fields = classObj.getFields();
		for(Field field : fields){
			System.out.println("Field: "+field.getName()+", access modifier="+field.getModifiers());
		}

		Field[] decFields = classObj.getDeclaredFields();
		for(Field field : decFields){
			System.out.println("Decl Field: "+field.getName()+", access modifier="+field.getModifiers());
		}

}



Output:
Field: i, access modifier=1
Decl Field: i, access modifier=1
Decl Field: j, access modifier=4
Decl Field: k, access modifier=2

getFields() method returns ONLY public fields (access modifier is 1) whereas getDeclaredFields() returns all fields irrespective of access modifier.
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}