1

The easiest to explain my problem is with an example. I have a compilation problem:

The method setOptions(ArgBuilder<Option<? extends Command>>) 
in the type Command is not applicable for the arguments (ArgBuilder<Option<T>>)

but T is declared as a generics that extends Command so I don't understand why this doesn't work. This compilation problem can be replicated with the 4 classes below, the compilation problem will appear in the Steps class I pasted at the c.setOptions(options); line.

I would like to know if there exist any way to workaround this compilation error.


package xyz.com; 

import java.lang.reflect.Constructor; 

public class Main { 

    public abstract class Option<T extends Command>{} 

    public abstract class Command{ 
        protected ArgBuilder<Option<? extends Command>> options; 

        void setOptions(ArgBuilder<Option<? extends Command>> options){ 
            this.options = options; 
        } 
    } 

    public class ArgBuilder<T extends Option<? extends Command>>{} 

    public class Steps<T extends Command>{ 
        protected Class<T> newCommandClass; 
        protected ArgBuilder<Option<T>> options; 

        public Command build(){ 
            try { 
                Constructor<T> ctor = newCommandClass.getConstructor(); 
                Command c = ctor.newInstance(); 
                c.setOptions(options); 
                return c; 
            } catch (Exception e) { 
                e.printStackTrace(); 
                return null; 
            } 
        } 
    } 

}
madx
  • 6,723
  • 4
  • 55
  • 59
  • 2
    Way too much code... please narrow it down to the **relevant** code – Dici Jun 27 '16 at 22:40
  • 1
    Not sure I agree with the duplicate. There is an attempt of mutation in the other question, which is not the case here. – Dici Jun 27 '16 at 22:50
  • Ok I cleaned the code, now it should be more readable – madx Jun 27 '16 at 22:51
  • Thanks ! I'm voting to reopen, this is not the same use-case. I think you're just hitting the limits of the Java compiler's type inference. You're gonna have to simplify your generics or accept some unsafety. You can also use reflective methods to explicitely cast the items – Dici Jun 27 '16 at 22:53
  • Yeah, I don't think that this is a duplicate of the signaled one... I hope that it will be reopened – madx Jun 27 '16 at 22:56
  • To anyone who reads this: i'd really appreciate if you could help me reopen the question by clicking 'reopen', thank you so much – madx Jun 28 '16 at 11:14
  • I just solved it using `ArgBuilder extends Option extends Command>>`instead of `ArgBuilder – madx Jun 28 '16 at 16:12

0 Answers0