简体   繁体   中英

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!

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) 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM