package net.sourceforge.tuned.ui; import java.lang.reflect.Method; import javax.swing.Icon; import net.sourceforge.tuned.ExceptionUtil; /** * IconProvider based on reflection. */ public class SimpleIconProvider implements IconProvider { private final Method getIconMethod; /** * Same as new SimpleIconProvider<T>(T.class). * * @return new IconProvider */ public static SimpleIconProvider forClass(Class type) { return new SimpleIconProvider(type); } /** * Create a new IconProvider which will use the getIcon method of the given * class. * * @param type a class with a getIcon method */ public SimpleIconProvider(Class type) { this(type, "getIcon"); } /** * Create a new IconProvider which will use a specified method of a given class * * @param type a class with the specified method * @param getIcon a method name such as getIcon */ public SimpleIconProvider(Class type, String getIcon) { try { getIconMethod = type.getMethod(getIcon); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Icon getIcon(T value) { try { return (Icon) getIconMethod.invoke(value); } catch (Exception e) { throw ExceptionUtil.asRuntimeException(e); } } }