dimanche 22 janvier 2017

Java reflection get anonymous class' origin interface

I have the following HashMap. Its purpose is to be used to invoke certain methods of classes extending JPanel. The method being the value in the HashMap and the parameter passed being the key.

HashMap<Object, String> methodMapper = new HashMap<>();

projectMethodMapper.put("Some title", "setInfoTitle");

projectMethodMapper.put(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("working");
    }
}, "attachListener");

This particular HashMap is to be used for a class called InfoPanel and it has the following methods.

public void attachListener(ActionListener al) {
    this.button.addActionListener(al);
}

public void setInfoTitle(String name) {
    ((TitledBorder) this.getBorder()).setTitle(name);
}

Later on I iterate through the keys of the HashMap.

InfoPanel infoPanel = new InfoPanel();

for (Object key : keys) {
    Method method = InfoPanel.class.getDeclaredMethod(methodMapper.get(key), key.getClass());

    method.invoke(infoPanel, key));
}

As you can imagine, there is no problem when the key is a String object, the problem comes when getDeclaredMethod searches for a method attachListener with parameter of type MainPanel$1 as .getClass returns MainPanel$1 because it's an anonymous class created on the fly. My question is - how do I find what interface is used for the creation of the anonymous class used for the object instantiation?





Aucun commentaire:

Enregistrer un commentaire