Is this possible somehow in Java, or am I only able to declare return types like this? I think Java has to type it also, somehow. I'd prefer not to resort to a wrapper like this, as it feels like cheating:

"I would like to have a pointer like this" - you can't. Variables have to be of a known (possibly erased) type, and a type constraint isn't a type
–
millimooseJan 22 '13 at 17:34

4

Also, you can't actually return anything from getFooBar() without casting it to (T), which should give you a hint that you're doing something wrong.
–
millimooseJan 22 '13 at 17:42

2

(Oddly enough, this discovered a bug in IntelliJ's code analysis engine, it only recognizes methods of Foo as valid.)
–
millimooseJan 22 '13 at 17:47

2

Could the downvoter please explain? This is an understandable and relatively well-written question.
–
Paul BelloraJan 22 '13 at 18:24

Just to clarify the bounty message, I'm specifically looking for a use case for a syntax like Foo&Bar bothFooAndBar = ... - that is using Foo&Bar as the type of a variable (like the question is asking for) or a return type.
–
Paul BelloraJan 30 '13 at 19:22

4 Answers
4

While the type parameters of a generic method can be restricted by bounds, such as extends Foo & Bar, they are ultimately decided by the caller. When you call getFooBar(), the call site already knows what T is being resolved to. Often, these type parameters will be inferred by the compiler, which is why you don't usually need to specify them, like this:

FooBar.<FooAndBar>getFooBar();

But even when T is inferred to be FooAndBar, that's really whats happening behind the scenes.

So, to answer your question, such a syntax like this:

Foo&Bar bothFooAndBar = FooBar.getFooBar();

Would never be useful in practice. The reason is that the caller must already know what T is. Either T is some concrete type:

Technically, that wraps up the answer. But I'd also like to point out that your example method getFooBar is inherently unsafe. Remember that the caller decides what T gets to be, not the method. Since getFooBar doesn't take any parameters related to T, and because of type erasure, its only options would be to return null or to "lie" by making an unchecked cast, risking heap pollution. A typical workaround would be for getFooBar to take a Class<T> argument, or else a FooFactory<T> for example.

Update

It turns out I was wrong when I asserted that the caller of getFooBar must always know what T is. As @MiserableVariable points out, there are some situations where the type argument of a generic method is inferred to be a wildcard capture, rather than a concrete type or type variable. See his answer for a great example of a getFooBar implementation that uses a proxy to drive home his point that T is unknown.

As we discussed in the comments, an example using getFooBar created confusion because it takes no arguments to infer T from. Certain compilers throw an error on a contextless call to getFooBar() while others are fine with it. I thought that the inconsistent compile errors - along with the fact that calling FooBar.<?>getFooBar() is illegal - validated my point, but these turned out to be red herrings.

Based on @MiserableVariable's answer, I put together an new example that uses a generic method with an argument, to remove the confusion. Assume we have interfaces Foo and Bar and an implementation FooBarImpl:

Now let's say we have a wildcard parameterized type of FooBarContainer:

FooBarContainer<?> unknownFooBarContainer = ...;

We're allowed to pass unknownFooBarContainer into unwrap. This shows my earlier assertion was wrong, because the call site doesn't know what T is - only that it is some type within the bounds extends Foo & Bar.

I can only guess that this is because wildcard captures can never match each other - the ? argument provided at the call site is ambiguous, with no way of saying that it should specifically match the wildcard in the type of unknownFooBarContainer.

So, here's the use case for the syntax the OP is asking about. Calling unwrap on unknownFooBarContainer returns a reference of type ? extends Foo & Bar. We can assign that reference to Foo or Bar, but not both:

This is just one fairly obscure use case. There would be pretty far-ranging implications for allowing such a syntax, both good and bad. It would open up room for abuse where it wasn't needed, and it's completely understandable why the language designers didn't implement such a thing. But I still think it's interesting to think about.

A note about heap pollution

(Mostly for @MiserableVariable) Here's a walkthrough of how an unsafe method like getFooBar causes heap pollution, and its implications. Given the following interface and implementations:

Here, when the new Foo2 is cast to T, it is "unchecked", meaning because of type erasure the runtime doesn't know it should fail, even though it should in this case since T was Foo1. Instead, the heap is "polluted", meaning references are pointing to objects they shouldn't have been allowed to.

The failure happens after the method returns, when the Foo2 instance tries to get assigned to the foo1 reference, which has the reifiable type Foo1.

You're probably thinking, "Okay so it blew up at the call site instead of the method, big deal." But it can easily get more complicated when more generics are involved. For example:

Now it doesn't blow up at the call site. It blows up sometime later when the contents of foo1List get used. This is how heap pollution gets harder to debug, because the exception stacktrace doesn't point you to the actual problem.

It gets even more complicated when the caller is in generic scope itself. Imagine instead of getting a List<Foo1> we're getting a List<T>, putting it in a Map<K, List<T>> and returning it to yet another method. You get the idea I hope.

If there is another static <U extends Foo & Bar> processFooBar(U u) I call it directly as processFooBar(getFooBar()). I haven't tried but I suspect the get can return a proxy that implements both Foo and Bar (I recoded the OP's example slightly) which means there may not actually be a named type that satisfies both constraints. So I don't understand why you say the caller must know what T is
–
Miserable VariableJan 25 '13 at 1:40

1

See pastebin.com/UGNvgjEZ. I realize this is not very difficult from your examples, but my point is that the client doesn't need to know the actual type T. It can call another method on the returned value and can assign it to either a Foo or Bar reference but not both. Doesn't that seem a syntax hole?
–
Miserable VariableJan 25 '13 at 1:50

Both FooBar1 and FooBar2 implement Foo and Bar. In main, the calls to getFooBar1 and getFooBar2 can be assigned to a variable, though there isn't a strong reason for it to know IMHO.

But getFooBar is the interesting case, which uses a proxy. In practice, it may be the only instance of a an object that implements the two interfaces. A different method (show here) can be used with a temporary in a type-safer manner, but it cannot be assigned to a variable without the FooBarWrapper hack described in the question. It is not even possible to create a generic wrapper, class Wrapper<T extends U & V> is not allowed.

The only trouble seems be defining a syntax, other type checking mechanisms seem to be in place, at least in Oracle javac 1.7.0.

Like @Paul Bellora mentioned in his answer, the type get resolved by the caller, since essentially it will now what it is calling. I would just like to add to his answer with an use case where I think the usage of the syntax could be of benefit.

There are always alternatives that avoid using such syntax. I cannot think of a single example that this is utterly necessary. However I can think of a use case of a particular situation that this syntax could be used conveniently, although I didn't even used it myself. I know its not the best example out there but it can get to the point.

Case

Recently I've been working in the development of an user interface. In this application I use a library to manage my GUI elements. In addition to the features of the library, I created a custom interface that defines a View in my application that has inputs for a specific type of data, lets say, input of coordinates. That interface would look like:

I have several windows across my application that implement this interface. Now lets say that for some reason I want to store in a model the last coordinate submitted in a window and close the window right after. For this I can attach a handler to the window button that submits the form, the handler will get triggered when the user closes the Window. I could achieve that by simply adding the handler anonymously in every window, like:

However, this design is not desirable for me, it is not modular enough. Considering I have a decent amount of windows with this behavior, changing it could get rather tedious. So I rather extract the anonymous method in a class so that it would be easier to change and maintain. But the problem is that the destroy() method is not defined in any interface, is just part of window and the getCoordinate() method is defined in the interface I defined.

Notice that the behavior will remain the same, the code is just a cohesive as it used to be. Its only more modular, but it didn't required the creation of an additional interface to be able to extract it properly.

Alternative

Alternatively, I could have defined an additional interface extending CoordinateView and define a method to close the window.

Having the window implement this more specific interface instead and making the making unnecessary the use of generic parameters in the extracted controller:
public class MyController implements ClickHandler
{
private CoordinateWindow windowWithCoordinates;

This approach for some can be seen as much cleaner than the previous and even more reusable since now it could be added to other "windows" outside of the specified hierarchy. Personally, I prefer this approach as well. However, it may result in a little more coding since a new interface has to be defined just for the sake of getting a access to a desired method.

In conclusion, although I personally don't recommend it I think using generic types with multiple bounds could help in coupling definitions while reducing the amount of code.

Ooooh, my bounty message must not have been clear. Sorry, but I specifically meant a use case for a syntax like Foo&Bar bothFooAndBar = ..., as in using Foo&Bar as the type of a variable (like the question is asking for) rather than generic bounds. Sorry, I should have made that more clear. +1 for a great example of using multiple generic bounds though.
–
Paul BelloraJan 30 '13 at 19:09

Oh, I'm sorry I didn't actually answered the question. I thought you meant the syntax in a more general case.
–
SednusJan 30 '13 at 19:22

If the bounty gets awarded automatically, I can always return it ;)
–
SednusJan 30 '13 at 19:23

2

Haha, you better or thugs are going to be knocking on your door demanding my points back :)
–
Paul BelloraJan 30 '13 at 19:27