Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot instantiate the type with regular Class

So I have a class:

public class DynQSimModule<T extends Mobsim> extends AbstractModule
{

   private Class<? extends javax.inject.Provider<? extends T>> providerClass;

   public DynQSimModule(Class<? extends javax.inject.Provider<? extends T>> providerClass)
   {
    this.providerClass = providerClass;
   }

   //some methods down here
}

And when I try to call:

controler.addOverridingModule(new DynQSimModule<>(AMoDQSimProvider.class));

Eclipse tells me it "cannot infer type arguments for DynQSimModule<>. I understand this is because I haven't put anything in the <>, but the example code I building off of uses the same exact syntax and runs perfectly fine...

When I put in something like:

controler.addOverridingModule(new DynQSimModule<? extends Mobsim(AMoDQSimProvider.class));

Eclipse tells me: "cannot instantiate the type DynQSimModule."

I know that this is a problem when you try and instantiate an interface or abstract class, but DynQSimModule is neither of those...

Any help would be great.

Thanks!

like image 293
Yousef Hindy Avatar asked Oct 30 '22 00:10

Yousef Hindy


1 Answers

I suppose you are using JDK 7. If that is the case new DynQSimModule<>(AMoDQSimProvider.class) will not compile because Java 7 does not use target typing to infer type of the passed parameter.

new DynQSimModule<? extends Mobsim>(AMoDQSimProvider.class) will also not compile because you cannot use wild card notation in object creation.

To resolve this either you have to provide exact type in new DynQSimModule<>(...) or if it is possible, you could upgrade to Java 8 which provides target type inference feature.

For example below code will not compile in Java 7 but will compile in Java 8+:

public static void test(List<String> list) {
   // some code
}

public static void main(String[] args) {
   test(new ArrayList<>());    // will not compile in Java 7 but it is legal in Java 8+
}

More on Java 8 Target Type Inference.

like image 69
justAbit Avatar answered Nov 13 '22 01:11

justAbit