0

I'm using TTS in my app. I want to run a method when I ask for it. I created a Hashtable where I want to store my methods like:

table.put("qqq", say("www"));

I'm comparing my data with keys - it works, but it does not trigger a method.

This probably isn't possible with Hashtable, so please tell me how to do what I want in the simplest way

ugo
  • 2,705
  • 2
  • 30
  • 34
Lau
  • 1,804
  • 1
  • 23
  • 49
  • 2
    You can store instances or types, e.g., an instance of an interface that has a `say` method. Look for "command pattern in Java" or something like that. – Dave Newton Mar 13 '14 at 17:54
  • 1
    possible duplicate of [How to call a method stored in a HashMap? (Java)](http://stackoverflow.com/questions/4480334/how-to-call-a-method-stored-in-a-hashmap-java) – ugo Mar 13 '14 at 18:08

3 Answers3

1

You should save the Object which calls that method:

Hashtable<String, MyObject> objects = new Hashtable<String, MyObject>();
objects.put("qqq",new MyObject());

MyObject test = objects.get("qqq");
test.say("www");
betteroutthanin
  • 7,148
  • 8
  • 29
  • 48
1

Check out java.lang.reflect, might be the right thing to use in your situation. With reflection you can do something like this:

Method method = myObject.getClass().getMethod("say", String.class);
method.invoke(myObject, "www");

So all you would need to do is store the object, method name, and parameters and then you can dynamically invoke the method.

Nyx
  • 2,233
  • 1
  • 12
  • 25
0

probably it is more a design issue.

Solution could be: if You are using only say() method, then store just a parameter that You would pass to the say() method (E.g., table.put("qqq", "www");). And when You need particular phrase to be found just call say(table.get("qqq"));.

Puzik
  • 1,423
  • 1
  • 10
  • 11