I would like to be able to call a specific static method (I.e. "void
do_something()") without having to specify the exact class at
compile time. The name and prototype of the static method is known
at compile time, the name of the class is known only at runtime.
Does anyone know how to do that ?
Thanks,
Morten M. Christensen
Odense Lindoe
No, I can not think of a way to do this. But if you relax the "static"
requirement, then you can use an interface with several implementations,
or use Class.forName().
Dick
Mach J, a clean room Java Virtual Machine
http://www.machj.com
My first reaction is "Why not use real objects?" What you just described
is the inherent behavior of:
anObject.do_something()
Where anObject is an object constructed from one of several classes that
each implements the interface:
public interface AtLeastDoSomething {
public void do_something();
}
So wouldn't that work for your needs? If the object does not need any
state information (instance variables), that is fine, and if you don't
need more than one object of each class around (a Singleton, see Design
Patterns by Gamma et. al.) you can handle that too. All you have left is
holding on to the different possible objects and deciding among them at
runtime. If you really don't know what classes could exist before
runtime, you can use the "forName()" method of Class to retrieve the class
at runtime and then instanciate an object and cast to your interface
before calling do_something().
The other approach -- if you don't want to use objects and interfaces --
is to use the JDK1.1 reflection capabilities to get to your static side
procedure. This is quite a bit more involved in setting up for the
"invoke" and has a significant performance penalty, but it will allow you
to postpone determining any/all aspects of the function (or method) call
until runtime.
--Mark
mark.f...@chimu.com
http://www.chimu.com/
PS: For the first option again, the worst case (assuming you don't want
the rest of the method clients to work with a Singleton) is that you have
a static method AND an object method that simply calls the static method
[Note: Java requires these methods to have different signatures (i.e.
static and object methods share the same name space)]
I can think of a way to do what you want. But my question is:
Why? Could you give an example of what you are trying to
do? Without details it sounds like you are trying to kludge
something together that shouldn't be.
( Two soulutions: Use reflection or declare an interface with
an instance method that calls your static method )
--
Michael S. Jenkins |
Jenkins Consulting Services, Inc. | So long, and thanks
mailto:mjen...@jcs-inc.com | for all the fish!
http://www.wwa.com/~mjenkins |