@Override public <T> T get(Enum key, Class<T> resultClass, T defaultValue) { if (defaultValue == null) { try { String def = key.getDeclaringClass().getField(key.name()).getAnnotation(Default.class).value(); if (resultClass == String.class) return (T) def; return resultClass.getConstructor(String.class).newInstance(def); } catch (Exception e) { throw new RegisteredExceptionWrapper(e); } } return defaultValue; }
@SuppressWarnings("unchecked") private static <T> List<T> loadServices(Class<T> clazz) { final Map<T, Double> services = new IdentityHashMap<T, Double>(); Enumeration<URL> resourceList; try { resourceList = clazz .getClassLoader() .getResources("META-INF/services/" + clazz.getName() + ".properties"); } catch (IOException e) { throw new RegisteredExceptionWrapper("Could not load resources for " + clazz, e); } while (resourceList.hasMoreElements()) { URL resource = resourceList.nextElement(); Properties properties = new Properties(); try { properties.load(resource.openStream()); } catch (IOException e) { LOG.log(Level.WARNING, "Could not load service list for " + clazz + " from " + resource, e); } for (Entry<Object, Object> e : properties.entrySet()) { T service; try { service = (T) Class.forName(e.getKey().toString()).newInstance(); } catch (Exception ex) { LOG.log( Level.WARNING, "Service " + e.getKey() + " defined in " + resource + " could not be loaded and was skipped", ex); continue; } Double priority; try { priority = Double.valueOf(e.getValue().toString()); } catch (NumberFormatException ex) { LOG.warning( "Service " + e.getKey() + " defined in " + resource + " has invalid priority " + e.getValue() + ": " + ex.getMessage() + " Default priority used"); priority = 0.0; } services.put(service, priority); } } List<T> rc = new ArrayList<T>(services.keySet()); Collections.sort( rc, new Comparator<T>() { public int compare(T o1, T o2) { return services.get(o2).compareTo(services.get(o1)); } }); return Collections.unmodifiableList(rc); }
public <T extends Enum<T>> T getSelected(Class<T> clazz) { Default d = clazz.getAnnotation(Default.class); return d != null ? Enum.<T>valueOf(clazz, d.value()) : clazz.getAnnotation(FirstIsDefault.class) != null ? clazz.getEnumConstants()[0] : null; }