If you have JComponents
Objects in your program other than JButton
, JMenuItem
and JToggleButton
that dot not extends AbstractButton
-Example JComboBox
- you may consider using Reflection
.
The idea is to keep two separate sets, one for the approvedClasses
and the second for the declinedClasses
which contains no such method signature.
In this way you save some time, because the method for searching the given method signature shall search in all classes in the tree of hierarchy of the given Class Component.
And because you have a form that contains a lot of components, the time is critical.
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JMenuItem;
public class SearchForAddActionListener{
// to save time, instead of searching in already-searched-class
static Set<Class<?>> approvedClasses = new HashSet<>();
static Set<Class<?>> declinedClasses = new HashSet<>();
public static boolean hasAddActionListener(JComponent component, String signature){
Class<?> componentClazz = component.getClass();
Class<?> clazz = componentClazz;
if(declinedClasses.contains(componentClazz)){return false;}
while(clazz!=null){
if(approvedClasses.contains(clazz)){
approvedClasses.add(componentClazz);// in case clazz is a superclass
return true;
}
for (Method method : clazz.getDeclaredMethods()) {
if(method.toString().contains(signature)){
approvedClasses.add(clazz);
approvedClasses.add(componentClazz);
return true;
};
}
clazz = clazz.getSuperclass(); // search for superclass as well
}
declinedClasses.add(componentClazz);
return false;
}
public static void main(String[] args) {
JComboBox<?> comboBox = new JComboBox<>();
JButton button = new JButton();
JMenuItem menuItem = new JMenuItem();
JList<?> list = new JList<>();
System.out.println(hasAddActionListener(comboBox,"addActionListener"));
System.out.println(hasAddActionListener(button,"removeActionListener"));
System.out.println(hasAddActionListener(menuItem,"addActionListener"));
System.out.println(hasAddActionListener(list,"addActionListener"));
System.out.println(approvedClasses);
System.out.println(declinedClasses);
}
}
Output
true
true
true
false
[class javax.swing.JButton, class javax.swing.JComboBox, class javax.swing.AbstractButton, class javax.swing.JMenuItem]
[class javax.swing.JList]