Re: Could you help on this reflection technique?
Shawn wrote:
I try to use interface Mapper approach to evoke action dynamically. But
I ran into an error:
//in the very top of my program
interface Mapper {
public void menuItemAction();
}
....
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand(); //get the string
"save1", or "save2", or "get1", or "get2", etc.
//Try to evoke different action dynamically, but:
((Mapper)actionCommand).menuItemAction(); //Error: cannot cast
a String into a Mapper
}
//Mapper definitions block
{
Mapper save1 = new Mapper()
{
public void menuItemAction()
{
memo1 = theText.getText();
}
};
Mapper save2 = new Mapper()
{
public void menuItemAction()
{
memo2 = theText.getText();
}
};
Mapper get1 ....
}//end of Mapper definition block
Thank you very much for your help. I greatly appreciate it.
It looks like what you want to do is create multiple Mapper instances
(which you have done), then save them in a Map, so you can look them up
using the actionCommand string.
e.g.
Map<String, Mapper> myActions = new HashMap<String, Mapper>();
// create your Mapper instances
myActions.put("save1", save1);
// link the String "save1" with the Mapper instance save1
myActions.put("save2", save2);
//etc
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
Mapper mapper = myActions.get(actionCommand);
mapper.menuItemAction();
}
Note that there is not really a need to define your own Mapper
interface, you might want to investigate the Action classes which do
this for you already.
Rogan