Invoking a method by name using Reflection

1

It is possible to use reflection to invoke a method using its name , which is known only at runtime . The following code demonstrates the usage of the invoke method . Note that reflection may be used to override the java access checks , allowing the caller to invoke methods that are declared private .


/** *PUBLIC SOFTWARE * *This source code has been placed in the public domain. You can use, modify, and distribute *the source code and executable programs based on the source code. * *However, note the following: * *DISCLAIMER OF WARRANTY * * This source code is provided "as is" and without warranties as to performance * or merchantability. The author and/or distributors of this source code may * have made statements about this source code. Any such statements do not constitute * warranties and shall not be relied on by the user in deciding whether to use * this source code.This source code is provided without any express or implied * warranties whatsoever. Because of the diversity of conditions and hardware * under which this source code may be used, no warranty of fitness for a * particular purpose is offered. The user is advised to test the source code * thoroughly before relying on it. The user must assume the entire risk of * using the source code. * */ import java.lang.reflect.*; /** * * @author amal * version 1.0 */ public class InvokeTest { public static void main(String[] args) throws Exception { Class c = Class.forName("X"); Object instance = c.newInstance(); Method m = c.getDeclaredMethod("A",new Class[]{}); m.invoke(instance, new Object[]{}); m = c.getDeclaredMethod("A",new Class[]{int.class});//or INTEGER.TYPE m.invoke(instance, new Object[]{1}); m = c.getDeclaredMethod("A",new Class[]{String.class}); m.invoke(instance, new Object[]{"arg"}); m = c.getDeclaredMethod("A",new Class[]{String.class,String.class}); m.setAccessible(true);//supress the java access check m.invoke(instance, new Object[]{"arg1","arg2"}); } } class X { void A() { System.out.println("In method A , with no arguments"); } void A(int i) { System.out.println("In method A , with an integer argument "+i); } void A(String s) { System.out.println("In method A , with a string argument "+s); } private void A(String s,String t) { System.out.println("In the private method A , with two string arguments "+s+" , "+t); } }

Read more »

1 comments:

  1. great post ...

    keep updating

Post a Comment

© Zone817. Powered by Blogger.