470,870 Members | 1,442 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,870 developers. It's quick & easy.

reference methods or fields by "name"

Is there any way of referencing a method or field dynamically by a name
contained in a string?

thanks
D
Jul 17 '05 #1
2 1421
You can use the java.land.reflect API to do this.

example:
Class clazz = Class.forName("xyz");
Object obj = clazz.newInstance();
Method meth = clazz.getMethod("toString", null);
Object ret = meth.invoke(obj, null);

danjourno wrote:
Is there any way of referencing a method or field dynamically by a name
contained in a string?

thanks
D

Jul 17 '05 #2
On Mon, 27 Sep 2004 00:01:11 +1000, danjourno wrote:
Is there any way of referencing a method or field dynamically by a name
contained in a string?

thanks
D


Method m = obj.getClass().getMethod(methodname, Object[] parameters)
returns the method you want to call on obj. To invoke it:
m.invoke(obj, Object[] parameters)

You can see the Method class in java.lang.reflect

Tony
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

16 posts views Thread by Gufus | last post: by
6 posts views Thread by Cecil | last post: by
13 posts views Thread by dhughey | last post: by
1 post views Thread by alain MONTMORY | last post: by
1 post views Thread by Terry Olsen | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.