Java tutorial
//package com.java2s; import javax.swing.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; public class Main { private static <T extends JComponent> T getComponentFromList(Class<T> clazz, List<T> list, String property, Object value) throws IllegalArgumentException { T retVal = null; Method method = null; try { method = clazz.getMethod("get" + property); } catch (NoSuchMethodException ex) { try { method = clazz.getMethod("is" + property); } catch (NoSuchMethodException ex1) { throw new IllegalArgumentException( "Property " + property + " not found in class " + clazz.getName()); } } try { for (T t : list) { Object testVal = method.invoke(t); if (equals(value, testVal)) { return t; } } } catch (InvocationTargetException ex) { throw new IllegalArgumentException( "Error accessing property " + property + " in class " + clazz.getName()); } catch (IllegalAccessException ex) { throw new IllegalArgumentException( "Property " + property + " cannot be accessed in class " + clazz.getName()); } catch (SecurityException ex) { throw new IllegalArgumentException( "Property " + property + " cannot be accessed in class " + clazz.getName()); } return retVal; } /** * Convenience method for determining whether two objects are either * equal or both null. * * @param obj1 the first reference object to compare. * @param obj2 the second reference object to compare. * @return true if obj1 and obj2 are equal or if both are null, * false otherwise */ public static boolean equals(Object obj1, Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); } }