Java generics - Make Generic to extends 2 interfaces
Asked Answered
C

2

59

How do you make this work:

public class Frankenstein<T extends IHuman, IMonster>{
}

Without making

public interface Weirdo extends Ihuman, IMonster{
}

Edit

Why is this not working?

public <T> void mapThis(
        Class<? extends MyClass<T>> key, Class<? extends T & IDisposable> value) {

}

I am getting compiler message marking Class<? extends T & IDisposable> as an Error.

Credence answered 27/10, 2012 at 16:31 Comment(1)
Possible duplicate of Java Generics Wildcarding With Multiple ClassesBenitobenjamen
C
124

Reimeus already pointed out that what you're asking for in your edit isn't possible. I'd just like to expand a little on why.

One would think you could use the following:

public <T, U extends T & IDisposable> void mapThis(
        Class<? extends MyClass<T>> key,
        Class<? extends U> value
) { ... }

In fact that's what came to my mind when I first saw this post. But this actually gives a compiler error:

a type variable may not be followed by other bounds

To help me explain why, I'd like to quote an Oracle Blogs post by Victor Rudometov about this error:

This fact is not always clear, but it is true. The following code should not compile:

interface I {}

class TestBounds <U, T extends U & I> {

}

Because JLS Chapter 4 Types, Values, and Variables section 4.4 Type Variables states: "The bound consists of either a type variable, or a class or interface type T possibly followed by further interface types I1 , ..., In.". So one may use T extends U, T extends SomeClass & I, but not T extends U & I. This rule applies to all cases including type variables and bounds in methods and constructors.

The reasons for this restriction are explored in a closely related post: Why can't I use a type argument in a type parameter with multiple bounds?

To summarize, the restriction was imposed in order to "preclude certain awkward situations coming into existence" (JLS §4.9).

What kind of awkward situations? An answer by Chris Povirk describes one:

[A reason for the restriction is] the possibility of specifying illegal types. Specifically, extending a generic interface twice with different parameters. I can't come up with a non-contrived example, but:

/** Contains a Comparator<String> that also implements the given type T. */
class StringComparatorHolder<T, C extends T & Comparator<String>> {
  private final C comparator;
  // ...
}
 
void foo(StringComparatorHolder<Comparator<Integer>, ?> holder) { ... }

Now holder.comparator is a Comparator<Integer> and a Comparator<String>.

Chris also points to Sun bug 4899305, which was a bug contesting this language restriction. It was closed as Won't Fix with the following comment:

If a type variable could be followed by type variables or by (possibly parameterized) interfaces, there would likely be more mutually recursive type variables, which are very difficult to handle. Things are already complicated when a bound is simply a parameterized type, e.g. <S,R extends Comparable<S>>. Consequently, bounds are not going to change now. Both javac and Eclipse agree that S&T and S&Comparable<S> are illegal.

So those are the reasons behind the restriction. Addressing generic methods specifically (which your question concerns), I'd like to further point out that type inference would theoretically cause such bounds to be pointless anyway.

If we reexamine the type parameters declared in the hypothetical signature above:

<T, U extends T & IDisposable>

Assuming the caller isn't explicitly specifying T and U, this can be reduced to the following:

<T, U extends Object & IDisposable>

Or just this (subtle difference, but that's another topic):

<T, U extends IDisposable>

This is because T doesn't have any bounds, so no matter what type of arguments get passed in, T can always resolve to Object at the very least, and so then can U.

Let's go back and say T is bounded:

<T extends Foo, U extends T & IDisposable>

This can be reduced in the same way (Foo could be a class or interface):

<T extends Foo, U extends Foo & IDisposable>

Based on that reasoning, the syntax you're trying to achieve is pointless as far as restricting the caller to more specific arguments.

Pre-Java 8 addendum:

Prior to Java 8, there is a use case for what you're trying to do. Because of a limitation with how the compiler infers generic method type parameters, my above reasoning to go out the window. Take the following generic method:

class MyClass {
    static <T> void foo(T t1, T t2) { }
}

This is a common beginner's mistake of trying to make a method that takes two parameters of the "same type". Of course it's pointless because of the way inheritance works:

MyClass.foo("asdf", 42); // legal

Here, T is inferred to be Object - this matches up with earlier reasoning about simplifying the mapThis type parameters. You have to manually specify the type parameters in order to achieve the intended type checking:

MyClass.<String>foo("asdf", 42); // compiler error

However, and here's where your use case starts to come in, it's a different matter with multiple type parameters with staggered bounds:

class MyClass {
    static <T, U extends T> void foo(T t, U u) { }
}

Now this call errors:

MyClass.foo("asdf", 42); // compiler error

The tables have turned - we have to manually relax the type parameters to get it to compile:

MyClass.<Object, Object>foo("asdf", 42); // legal

This happens because of the limited way in which the compiler infers method type parameters. For this reason, what you wanted to achieve would've actually had an application in restricting the caller's arguments.

However, this problem appears to have been fixed in Java 8, and MyClass.foo("asdf", 42) now compiles without any error (thanks to Regent for pointing this out).

Chantellechanter answered 7/11, 2012 at 0:41 Comment(4)
By the way, MyClass.foo("asdf", 42) doesn't give compile error with <T, U extends T> bounds in Java 8.Glister
@Glister nice to see that issue was fixed. Updated my answer, thanks!Chantellechanter
Good answer, even if I do not share it myself. In my opinion it is a design flaw in the compilerSimilar
Long story short, instead of adding detection for awkward situations, and giving a compile error, they decided to do nothing and forbid --- on which both Eclipse and Java devs agreed ;-)Mythomania
A
5

I just thought I would share my hack that I use in these (pretty rare) situations:

    /**
     * This is a type-checking method, which gets around Java's inability
     * to handle multiple bounds such as "V extends T & ContextAware<T>".
     *
     * @param value initial value, which should extends T
     * @param contextAware initial value, which should extend ContextAware<T>
     * @return a new proxy object
     */
    public T blah(T value, ContextAware<T> contextAware) {
        if (value != contextAware) {
            throw new IllegalArgumentException("This method expects the same object for both parameters.");
        }

        return blah(value);
    }

So by requiring the same object for each of the bounds you are trying to satisfy, you get the compile-time type checking and the single object which does everything. Admittedly it's a bit silly to pass the same object in for each parameter, but I do this in my 'internal' code quite safely and comfortably.

Aparejo answered 28/6, 2013 at 15:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.