Home > Code, General, Java > Java Reflection Examples

Java Reflection Examples

Just to clear the air we are not talking about some funky new graphics render we are talking about programmatic reflection access of variables and methods :)

1. All of the variables public or private in a class can be accessed via reflection, it is assumed for this example that the code is in a class with class variables, hence the usage of “this” (but it doesn’t have to be it could be an instance object). Although we are only echoing the variable name and value to the screen we could be assigning them using the setter functions in the Field class. Really practical usage of this functionality is automatic population of Model classes from the Data Access layer, for example when using SOAP.

for(int i=0;i< this.getClass().getDeclaredFields().length;i++){
	try {
		String varName = this.getClass().getDeclaredFields()[i].getName();
		Field field = this.getClass().getDeclaredField(varName);
		field.setAccessible(true);
				
		try {
			System.out.print("Variablename: " + varName + "\n");
			System.out.print("Value: " + field.get(this).toString() + "\n");
		} 
		catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} 
	catch (SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	catch (NoSuchFieldException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

2. This is an example of invoking a method via reflection, again this code assumes you are in a class. Also that class should contain a method called “test” with one String and an argument.

Class<?> params[] = {String.class};
		
try {
	Method method = this.getClass().getDeclaredMethod("test",params);
	try {
		method.invoke(this,"argument!!!!!");
	} 
	catch (IllegalArgumentException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	catch (IllegalAccessException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	catch (InvocationTargetException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
} 
catch (SecurityException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} 
catch (NoSuchMethodException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

Test function to be called via reflection.

public void test(String str){
	System.out.print("Method test invoked via reflection with arg: " + str);
}
Categories: Code, General, Java Tags: ,
  1. No comments yet.
  1. No trackbacks yet.
*