Tuesday, 22nd June 2010
The new frontier for learning Java

Class and static Method Reflection example

From WikiJava

Jump to: navigation, search
The author suggests:

buy this book


This example shows how easy is in Java to use reflection for executing a method in a class.

In the example both the class and the method names are specified via strings.

The method used in the example includes also a String parameter to be passed in and it returns another String.

Contents

the article

This example is composed of two class files:

Reflection
containing the main method and executing all the fun part
DynamicallyPointedClass
containing the method to be called, it's a very easy dummy class

Inside the main method of Reflection you can notice the steps required:

  1. obtain the java.lang.Class object containing the uninstantiated class
  2. obtain from the java.lang.Class the java.lang.reflect.Method that we will want to execute
  3. execute the invoke() of the method with the parameters
  4. output the resulting object.

note that:

  1. we don't know a priori the type of class1 so to make it generic proof we need to assign to it a type Class<?>
  2. we don't know a priori the type returned by method so it will be assigned to an object. Ready eventually to be casted to some more appropriate type.
  3. the reflection throws a bunch of different Exceptions, lot of things may go wrong in this process

DynamicallyPointedClass

Image:250px-Subversion.png
You can download the complete code of this article from the Subversion repository at this link

Using the username:readonly and password: readonly

See the using the SVN repository instructions page for more help about this.
package com.wikijava.reflection.pointed;
 
/**
 * this is the dummy class containing a method it serves as example for the
 * reflection the class implements the method <b>method</b> that will be called
 * by the reflection procedures
 * 
 * @author Giulio
 */
public class DynamicallyPointedClass {
    private static final String HELLO = "Hello "; //$NON-NLS-1$
 
    /**
     * 
     * simply gets a String and returns another String
     * 
     * @param name
     * @return a String
     */
    public static String method(String name) {
	return HELLO + name;
    }
}

Reflection

package com.wikijava.reflection;
 
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
/**
 * this example executes dynamically a method on a class, the class is
 * dynamically choosen via a string, and so is the method
 * 
 * 
 * @author Giulio
 */
public class Reflection {
 
    private static final String NAME = "Giulio"; //$NON-NLS-1$
 
    private static final String METHOD = "method"; //$NON-NLS-1$
 
    private static final String CLASS = "com.wikijava.reflection.pointed.DynamicallyPointedClass"; //$NON-NLS-1$
 
    /**
     * @param args
     */
    public static void main(String[] args) {
 
	Class<?> class1;
	try {
	    class1 = Class.forName(CLASS);
	    Method method = class1.getMethod(METHOD, String.class);
	    Object o = method.invoke(null, NAME);
	    System.out.println(o);
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	} catch (IllegalArgumentException e) {
	    e.printStackTrace();
	} catch (IllegalAccessException e) {
	    e.printStackTrace();
	} catch (InvocationTargetException e) {
	    e.printStackTrace();
	} catch (SecurityException e) {
	    e.printStackTrace();
	} catch (NoSuchMethodException e) {
	    e.printStackTrace();
	}
 
    }
 
}


Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

Alex - 3 Point(s)

Hi, I like the article but I'd like to add some kind of context. Situations in which reflection could be useful (just a link to another article that uses reflection in the see also would be enough)


Thanks

it is indeed my intention to write more about reflection, I've got almost ready a great example about instanciating classes using reflection. That will be easier to contextualize.

--DonGiulio 11:56, 28 May 2008 (PDT)


Static methods

Thanks i was looking for a way to call the static method of a class.

--Saurabh

--202.80.51.226 08:17, 25 March 2009 (UTC)


Qasouuol

this post is fantastic

--203.189.116.27 07:40, 25 April 2009 (UTC)


Title (required):

Website:

Comment: