DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Reflection - Get Vs GetDeclared Methods

09.16.2009
| 4904 views |
  • submit to reddit
        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());
		}

}


<b>Output</b>:
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.