Dynamic Casting again with array

U

u.Shanker

Hello !
Ok. I did my homework, by readin around, but not able to make it generic.
Problem:
I have to call ExternalClass.myMethod(InputClass[]);
Now depending on the cases InputClass and myMethods are different.
So I want to reflection.

Solution:
ExternalClass external = ...
InputClass rr = .....
InputClass[] array = new InputClass[] { rr };

GenerateProtocolObject generator = new GenerateProtocolObject(); // does the
Class.forName(classname)
Object o =generator.getObjectInstance("InputClass");

Class cls = Class.forName("InputClass");
Object arr = Array.newInstance(cls, 1); // just trying with 1 element in
array
Array.set(arr, 0, o);
Class c = external.getClass();
Class[] parameterTypes = new Class[] {array}; // <-- this works

Method concatMethod;
Object[] arguments = new Object[] { };
try {
Method[] mm = c.getMethods();
concatMethod = c.getMethod("myMethod", parameterTypes);

--
but I want something like
Class[] parameterTypes = new Class[] {o.getClass()};
Class[] parameterTypes = new Class[] {o[]};
Class[] parameterTypes = new Class[] {arr};

thanks for any comments
uma
 
J

John C. Bollinger

u.Shanker said:
Hello !
Ok. I did my homework, by readin around, but not able to make it generic.
Problem:
I have to call ExternalClass.myMethod(InputClass[]);
Now depending on the cases InputClass and myMethods are different.
So I want to reflection.

No, you don't. Really. It's the number one rule of Java reflection:
you don't want to use it. If you find yourself _needing_ to use it then
you should be at least grumpy about it, and preferably downright disturbed.
Solution:
ExternalClass external = ...
InputClass rr = .....
InputClass[] array = new InputClass[] { rr };

Fortunately for you, ExternalClass is apparently known at compile time,
so you don't, in fact, need reflection. You can create your own method
(or methods) on one of your own classes that accepts the argument and
evaluates the cases sufficiently to dispatch a normal method call to the
correct method of ExternalClass. This will be easier to write and
maintain, and chances are that it will perform better (reflection these
days is fairly fast, but you still have to do extra work in choosing the
correct Method object, setting up the arguments to the method
invocation, etc.). This technique is an implementation of the Class
Adapter design pattern.


John Bollinger
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top