javajava-7javac

Compiler change in Java 7


In Java 6 I was able to use:

public static <T, UK extends T, US extends T> T getCountrySpecificComponent(UK uk, US us) {
    Country country = CountryContext.getCountry();
    if (country == Country.US) {
        return us;
    } else if (country == Country.UK) {
        return uk;
    } else {
        throw new IllegalStateException("Unhandled country returned: "+country);
    }
}

With these repositories:

public interface Repository{
   List<User> findAll();
}

public interface RepositoryUS extends Repository{}

public interface RepositoryUK extends Repository{}

When using these:

RepositoryUK uk = ...
RepositoryUS us = ...

This line compiles in in Java6 but fails in Java7 (error cannot find symbol - as the compiler looks for findAll() on class Object)

List<User> users = getCountrySpecificComponent(uk, us).findAll();

This compiles in Java 7

List<User> users = ((Repository)getCountrySpecificComponent(uk, us)).findAll();

I know this is a rather uncommon use case but is there a reason for this change? Or a way to tell the compiler to be a little "smarter"?


Solution

  • I think T should be bounded to extend Repository. This way the compiler knows that getCountrySpecificComponent returns some repository.

    EDIT:

    It should also be ok to write: public static <T extends Repository> T getCountrySpecificComponent(T uk, T us)