package net.sourceforge.tuned.ui; import java.lang.reflect.Method; import java.util.Arrays; import javax.swing.Icon; import net.sourceforge.tuned.ExceptionUtil; /** * LabelProvider based on reflection. */ public class SimpleLabelProvider implements LabelProvider { private final Method getIconMethod; private final Method getTextMethod; /** * Factory method for {@link #SimpleLabelProvider(Class)}. * * @return new LabelProvider */ public static SimpleLabelProvider forClass(Class type) { return new SimpleLabelProvider(type); } /** * Create a new LabelProvider which will use the getText, getName * or toString method for text and the getIcon method for the * icon. * * @param type a class that has one of the text methods and the icon method */ public SimpleLabelProvider(Class type) { getTextMethod = findAnyMethod(type, "getText", "getName", "toString"); getIconMethod = findAnyMethod(type, "getIcon"); } /** * Create a new LabelProvider which will use a specified method of a given class * * @param type a class with the specified method * @param getText a method name such as getText * @param getIcon a method name such as getIcon */ public SimpleLabelProvider(Class type, String getText, String getIcon) { getTextMethod = findAnyMethod(type, getText); getIconMethod = findAnyMethod(type, getIcon); } private Method findAnyMethod(Class type, String... names) { for (String name : names) { try { return type.getMethod(name); } catch (NoSuchMethodException e) { // try next method name } } throw new IllegalArgumentException("Method not found: " + Arrays.toString(names)); } @Override public String getText(T value) { try { return (String) getTextMethod.invoke(value); } catch (Exception e) { throw ExceptionUtil.asRuntimeException(e); } } @Override public Icon getIcon(T value) { try { return (Icon) getIconMethod.invoke(value); } catch (Exception e) { throw ExceptionUtil.asRuntimeException(e); } } }