Java – pass the parameterized class instance to the constructor
I have lost my way through the jungle, please help me:) I have such a thing:
public class BaseClass<TYPE> { public BaseClass(Class<TYPE> clazz) {}; } public class FirstLevelClass<REFRESHABLE extends RefreshableInterface> extends BaseClass<REFRESHABLE> { public FirstLevelClass(Class<REFRESHABLE> clazz) { super(clazz); }; } public class Argument<T extends AnyOtherClass> implements RefreshableInterface { public refresh() {} } pulbic class ProblematicClass extends FirstLevelClass<Argument<AnyOtherClassDescendant>> { public ProblematicClass() { //Compiler error: Constructor //FirstLevelClass<Argument<AnyOtherClassDescendant>>(Class<Argument>) is undefined super(Argument.class); } }
As far as I know, the compiler should accept parameters because it implements refreshableinterface
>Why did I get this error? > How to make problem work?
PS: if you have a better title, please change it I can't make up for it better
Solution
The problem is that your constructor expects class < T >, and T in your code is inferred as argument < anyotherclassdescendant >
Therefore, you should pass a class < argument < anyotherclassdescendant > >, and you are passing class & argument > However, you cannot directly pass this class instance because you cannot execute argument < anyotherclassdescendant > class.
However, you can solve the problem by converting the class type to the desired instance:
public ProblematicClass() { super((Class<Argument<AnyOtherClassDescendant>>)(Class<?>)Argument.class); }
Notice how you type the class < argument > first to class < >, and then classify the result type to class < argument < anyotherclassdescendant > > There is no easy way to do this
The reason for this is that for all parameterized instantiations of a generic type, there is only one class instance associated with the class itself A single compilation unit of a common type is only compiled into a single class file I guess the C implementation template is different You can get different machine code in different instances
Therefore, if you execute the following code, you will get true as the output:
List<String> strList = new ArrayList<String>(); List<Integer> intList = new ArrayList<Integer>(); boolean isSameClassInstance = strList.getClass() == intList.getClass(); System.out.println(isSameClassInstance);