• Post Reply Bookmark Topic Watch Topic
  • New Topic

Use 'String' as method name  RSS feed

 
Max Simpson
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am trying to create a String and then that String name to call a method. See below it makes more sense:

String command = "set" + node.getNodeName();
book.command(node.getNodeValue());

My 'book' object does not have a method called 'commmand'. It has a method called 'setTitle'. The String named 'command' is trying to combine "set" with a returned node name (in this case, it is 'Title'), so 'command' has the value 'setTitle'.

On the next line, I want to call 'book.setTitle()', using my 'command' variable. Is there any way to do this?

Thanks!
 
pascal betz
Ranch Hand
Posts: 547
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi


look into the stuff in the java.lang.reflect package. There you have a Method object you can invoke.
You can obtain the methods from the Class object. Something like (this was only compiled by my head...)


of course you need to deal with various exception situation (e.g. if there is no setXYZ method in your class). also if your getNodeValue() returns a primitive value, then you can of course not call getClass() on it ...)

i hope this helps to get you started.
pascal
 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Max Simpson:
<snip> Is there any way to do this?


As pascal has shown, there are ways to do it. My question to you (and to the guy who squirts milk out of his eyes) is "Why would you want to do that?" There must be a simpler, more elegant way of having fun with Java (or using milk) than that...
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh, there are reasons.
For example I've created part of a persistence mechanism that calls a method returning an array of Strings containing methodnames on classes implementing a specific interface and persists the results of those methods.

Such things are pretty lowlevel and a bit archaic of course, and many people may never have a need to do something like it.


 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!