This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Execute the contents of a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Execute the contents of a String" Watch "Execute the contents of a String" New topic

Execute the contents of a String

Adelaide Clark

Joined: Mar 25, 2001
Posts: 2
How can I execute the contents of a String? I have an unusual JTree in that a node is actually a java command. When a node is selected, I want to execute the command that is the name of the node. I know that I could keep an array of all the commands and obtain the count of how many next siblings there are and, thereby, know which node is selected and use it in a bunch of if statements -- or do a comparison until I find a match, also, using if/case statements. While this is possible, it is cumbersome. Isn't there some way I can just make the contents an executable statement?
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
While this is possible using the Java Reflection API, it's not easy, and usually not a good idea.
The usual way to do this is to actually store an object instead of a string with each of your nodes. This object can be anything as long as they all implement the same interface, for example:

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Adelaide Clark

Joined: Mar 25, 2001
Posts: 2
Thank you. I appreciate your reply. I will try it.
I agree. Here's the link:
subject: Execute the contents of a String
jQuery in Action, 3rd edition