Unable to instantiate 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 that "it cannot call type arguments for DynQSimModule <>. I understand this because I did not put anything in <>, but the code for the example I'm building uses the same exact syntax and works fine fine .. .

When I add something like:

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

Eclipse tells me: "It is not possible to create an instance of type DynQSimModule."

I know this is a problem when you try to instantiate an interface or abstract class, but the DynQSimModule is neither one nor the other ...

Any help would be great.

Thanks!

+5
source share
1 answer

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

new DynQSimModule<? extends Mobsim>(AMoDQSimProvider.class) new DynQSimModule<? extends Mobsim>(AMoDQSimProvider.class) also not compile, because you cannot use the map legend in object creation.

To solve this problem, you must specify the exact type in new DynQSimModule<>(...) or, if possible, you can upgrade to Java 8, which provides a target type inference function.

For example, the code below 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+ } 

Learn more about Java 8 Target type query .

+2
source

All Articles