Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stackoverflow.generics;
- import java.lang.reflect.ParameterizedType;
- import java.lang.reflect.Type;
- public class GenericProcessor {
- public static void main(String[] args) {
- SomeProcessor proc = new SomeProcessor();
- proc.process(new SomeFoo());
- }
- interface Processor<T extends Foo> {
- void process(T foo);
- }
- static class SomeProcessor implements Processor<SomeFoo> {
- public void process(SomeFoo foo) {
- foo.setProcessor(this);
- }
- }
- interface Foo {
- void setProcessor(Processor<?> processor);
- Processor<? extends Foo> getProcessor();
- }
- static class SomeFoo implements Foo {
- Processor<SomeFoo> processor;
- public Processor<? super SomeFoo> getProcessor() {
- return processor;
- }
- @SuppressWarnings("unchecked")
- @Override
- public void setProcessor(Processor<?> processor) {
- Type type = ((ParameterizedType) processor.getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
- if (!getClass().equals(type))
- throw new RuntimeException(type.toString());
- this.processor = (Processor<SomeFoo>) processor;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement