Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics incompatible types for the exact same class

Tags:

java

generics

Here is an example of my Java code:

package com.company;

public class Main {

    private static class Something<T>{
        public void fun(Class<T> someClass){
            someClass.cast(null);
        }
    }
    private interface Hello{}

    public static void some(Something<? extends Hello> mySomething, Class<? extends Hello> myClass){
        mySomething.fun(myClass);
    }
}

And I'm getting a weird error at the mySomething.fun(myClass) line:

Required type: Class<? extends com.company.Main.Hello>
Provided: Class<? extends com.company.Main.Hello>

Which are the exact same type...

What am I missing here?

like image 687
Matan Kintzlinger Avatar asked Oct 27 '25 10:10

Matan Kintzlinger


1 Answers

I believe the problem is that the question mark in the "required" and "provided" can be different. Suppose I have two implementations of Hello: Hello1 and Hello2. I could call:

some(new Something<Hello2>(), Hello1.class);

That fulfills the contract of some, but you don't want to be able to call new Something<Hello2>().someClass(Hello1.class).

I believe you need to express the constraint once, by making some generic:

public static <T extends Hello> void some(Something<T> mySomething, Class<T> myClass)

Now the two parameters are appropriately related, so the call to fun is valid.

like image 78
Jon Skeet Avatar answered Oct 29 '25 23:10

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!