// Making an Object of the class className Class classObj = Class.forNam(className); Class loadParametersTypes = new Class; loadParametersTypes = Class.forName("java.lang.String"); // Getting the 'Method' using Reflection API Method loadMethod = classObj.getMethod("load", loadParametersTypes); Object loadParameters = new Object; loadParameters = (Object) new String(cacheName); // Invoking the required method loadMethod.invoke(null, loadParameters);
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
This code fragment demonstrates how Reflection can be used to load a class and invoke one of its methods by indirect means. To do this, one has to get object references to the essential components -- a Class object that represents the class containing the method, a reference to the method that allows us to see it as an object, and a list of references to the parameter types that help identify the method. Remember that in Java a method is uniquely identified by the number, order, and type of its parameters. The code that's given is a fragment, but there's still something missing that would make it appear workable; we can't invoke a method without an instance, either directly or indirectly. The only exceptions to this rule are methods declared static. So somewhere in this piece I expect to see a call newInstance() on the initial class' Class reference. ------------------ Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
Make visible what, without you, might perhaps never have been seen. - Robert Bresson
Joined: Jul 11, 2001
The code that's given is a fragment, but there's still something missing that would make it appear workable; we can't invoke a method without an instance, either directly or indirectly. The only exceptions to this rule are methods declared static. So somewhere in this piece I expect to see a call newInstance() on the initial class' Class reference.
Obviously the load-Method invoked is a static method - therefore the null-Parameter in invoke. [This message has been edited by Ilja Preuss (edited September 14, 2001).]
The code is not compilable. There is typo in it. I think that copy/paste from a working program is a more responsible way to do it. SCJD Study Group has been moved to http://www.developergroup.org/ [This message has been edited by Roseanne Zhang (edited September 15, 2001).]