This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
// Making an Object of the class className Class classObj = Class.forNam(className); Class[] loadParametersTypes = new Class[1]; loadParametersTypes[0] = Class.forName("java.lang.String"); // Getting the 'Method' using Reflection API Method loadMethod = classObj.getMethod("load", loadParametersTypes); Object[] loadParameters = new Object[1]; loadParameters[0] = (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
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
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).]
Roseanne Zhang
Ranch Hand
Joined: Nov 14, 2000
Posts: 1953
posted
0
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).]