Re: Question about java method calling
Re: Question about java method calling
- Subject: Re: Question about java method calling
- From: Fabrice Truillot <email@hidden>
- Date: Thu, 7 Oct 2004 02:13:56 +0200
<x-tad-smaller>On 7 oct. 04, at 00:30, Kevin Xiaowen Ren wrote:
</x-tad-smaller><x-tad-smaller>Could I know the code for " The default implementation of WODirectAction's performActionName() appends "Action" to the method's argument. "?
I am trying to call some dynamic method by method name string in class.?
</x-tad-smaller>
<x-tad-smaller>
Well, since we don't have the WebObjects source we have to write something by ourself...
</x-tad-smaller><x-tad-smaller>Finding the method `name` for the class `clazz` :
</x-tad-smaller><x-tad-smaller> </x-tad-smaller><x-tad-smaller>import</x-tad-smaller><x-tad-smaller> java.lang.reflect.*;
</x-tad-smaller><x-tad-smaller>
Method findMethod (String name, Class clazz)
{
Method[] methods = clazz.getMethods ();
</x-tad-smaller><x-tad-smaller>for</x-tad-smaller><x-tad-smaller> (</x-tad-smaller><x-tad-smaller>int</x-tad-smaller><x-tad-smaller> loop = </x-tad-smaller><x-tad-smaller>0</x-tad-smaller><x-tad-smaller>; loop < methods.length; ++ loop)
{
</x-tad-smaller><x-tad-smaller>if</x-tad-smaller><x-tad-smaller> (</x-tad-smaller><x-tad-smaller>methods[loop].getName ()</x-tad-smaller><x-tad-smaller>.equals (name)) </x-tad-smaller><x-tad-smaller>return</x-tad-smaller><x-tad-smaller> method;
}
</x-tad-smaller><x-tad-smaller>return null</x-tad-smaller><x-tad-smaller>;
}
</x-tad-smaller><x-tad-smaller>Method invocation :
</x-tad-smaller><x-tad-smaller>
Object target = ...
Method method = findMethod (</x-tad-smaller><x-tad-smaller>"myMethodByName"</x-tad-smaller><x-tad-smaller>, target.getClass ());
Object result = method.invoke (target, </x-tad-smaller><x-tad-smaller>new</x-tad-smaller><x-tad-smaller> Object[] { `method arguments` })
</x-tad-smaller><x-tad-smaller>
Pretty easy, isn't it ? Reflection is a very powerful feature, but can be costly so be careful. :)
</x-tad-smaller><x-tad-smaller>--
Fabrice Truillot
Men in Silicium Ltd. - </x-tad-smaller><x-tad-smaller>ケイ素の人</x-tad-smaller> _______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden