Advertisement
raffaele181188

Generics Processor

Nov 29th, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package stackoverflow.generics;
  2.  
  3. import java.lang.reflect.ParameterizedType;
  4. import java.lang.reflect.Type;
  5.  
  6. public class GenericProcessor {
  7.  
  8.     public static void main(String[] args) {
  9.         SomeProcessor proc = new SomeProcessor();
  10.         proc.process(new SomeFoo());
  11.     }
  12.  
  13.     interface Processor<T extends Foo> {
  14.         void process(T foo);
  15.     }
  16.  
  17.     static class SomeProcessor implements Processor<SomeFoo> {
  18.         public void process(SomeFoo foo) {
  19.             foo.setProcessor(this);
  20.         }
  21.     }
  22.  
  23.     interface Foo {
  24.         void setProcessor(Processor<?> processor);
  25.         Processor<? extends Foo> getProcessor();
  26.     }
  27.  
  28.     static class SomeFoo implements Foo {
  29.         Processor<SomeFoo> processor;
  30.        
  31.         public Processor<? super SomeFoo> getProcessor() {
  32.             return processor;
  33.         }
  34.        
  35.         @SuppressWarnings("unchecked")
  36.         @Override
  37.         public void setProcessor(Processor<?> processor) {
  38.            
  39.             Type type = ((ParameterizedType) processor.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
  40.            
  41.             if (!getClass().equals(type))
  42.                 throw new RuntimeException(type.toString());
  43.            
  44.             this.processor = (Processor<SomeFoo>) processor;
  45.         }
  46.     }
  47.    
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement