tterrag1098

Untitled

Jun 16th, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. @SuppressWarnings("rawtypes")
  2. public abstract class HandleGenericType<T> implements IHandler<T> {
  3.  
  4.   @SuppressWarnings("unchecked")
  5.   protected final List<IHandler>[] subHandlers = (List<IHandler>[]) new List[getRequiredParameters()];
  6.  
  7.   protected HandleGenericType(Type... parameterTypes) throws NoHandlerFoundException {
  8.     if (parameterTypes.length == 0) {
  9.       return;
  10.     }
  11.     if (parameterTypes.length != getRequiredParameters()) {
  12.       throw new IllegalArgumentException("Mismatch of parameter count. Required: " + getRequiredParameters() + "  Found: " + parameterTypes.length);
  13.     }
  14.     for (int i = 0; i < getRequiredParameters(); i++) {
  15.       Type type = parameterTypes[i];
  16.       try {
  17.         List<IHandler> handlers = Registry.GLOBAL_REGISTRY.findHandlers(type);
  18.         if (handlers.isEmpty()) {
  19.           throw new NoHandlerFoundException(type, "Unknown");
  20.         }
  21.         subHandlers[i] = handlers;
  22.       } catch (IllegalAccessException | InstantiationException e) {
  23.         throw new NoHandlerFoundException(type, "Unknown", e);
  24.       }
  25.     }
  26.   }
  27.  
  28.   @Override
  29.   public abstract Class<?> getRootType();
  30.  
  31.   protected abstract IHandler<? extends T> create(Type... types) throws NoHandlerFoundException;
  32.  
  33.   protected int getRequiredParameters() {
  34.     return 1;
  35.   }
  36.  
  37.   protected boolean canHandle(Type type) {
  38.     return !IHandler.isAssignable(getRootType(), type);
  39.   }
  40.  
  41.   @Override
  42.   public IHandler<? extends T> getHandler(Type type) {
  43.     if (!canHandle(type)) {
  44.       return null;
  45.     }
  46.    
  47.     if (type instanceof ParameterizedType) {
  48.       try {
  49.         return create(((ParameterizedType) type).getActualTypeArguments());
  50.       } catch (NoHandlerFoundException e) {
  51.       } // Fallthrough to return null
  52.     }
  53.  
  54.     return null;
  55.   }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment