How to set a class argument?

Hello
Prompt, who knows how to make a class argument? Probably not quite correctly expressed question, below example can explain this:
I have a method that changes the listener of the buttons:
void changeListeners(ArrayList<jbutton> buttons, Object className) {
 ActionListener[] listeners;
 for (JButton btn:buttons) {
 listeners = btn.getActionListeners();
 for (ActionListener l:listeners) {
btn.removeActionListener(l);
}
 btn.addActionListener(new className.getClass()); //you know what this design can do everything to break
}
 }</jbutton>


but because the new audience is different, then the argument need to serve the class, which will be the listener.
Thank you
July 2nd 19 at 17:39
2 answers
July 2nd 19 at 17:41
Solution
Maybe you know what it's for class, then you can do
reflective
void changeListeners(
 List<jbutton> buttons
 Class<? extends ActionListener--> clazz
) throws InstantiationException,an illegalaccessexception {
 ActionListener[] listeners;
 for (JButton b : buttons) {
 listeners = b.getActionListeners();
 for (ActionListener l : listeners) {
b.removeActionListener(l);
}
b.addActionListener(clazz.newInstance());
}
}
// call so
changeListeners(..., MySuperiorActionListener.class);</jbutton>


But if you are using Java 8 you can do
functionally
void changeListeners(
 List<jbutton> buttons
 Supplier<? extends ActionListener--> listenerConstructor
) {
 ActionListener[] listeners;
 for (JButton b : buttons) {
 listeners = b.getActionListeners();
 for (ActionListener l : listeners) {
b.removeActionListener(l);
}
b.addActionListener(listenerConstructor.get());
}
}
// apply so
changeListeners(..., MySuperiorActionListener::new)</jbutton>

thank you - margarette_Wiso commented on July 2nd 19 at 17:44
July 2nd 19 at 17:43
so easy is search
this.getClass().getClassLoader().loadClass("package.classname").newInstance();
OK I'll try thanks - margarette_Wiso commented on July 2nd 19 at 17:46

Find more questions by tags SwingJava