MetalSnake
MetalSnake

Reputation: 315

Difference between Java generics syntax?

What is the difference between these method definitions?

public <T extends Foo> void loadData(Class<T> p_class);

public void loadData(Class<? extends Foo> p_class);

Upvotes: 3

Views: 95

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

There is a difference in syntactic usage, as the second method has a generic type parameter.

class Bar extends Foo { }

obj.<Bar>loadData(klazz);

This requires klazz to be Class<Bar> exactly.

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

Both signatures accept exactly the same set of arguments, so in that sense are equivalent. As pointed out in the comments, in the second case you will not be able to refer to T in the body of the method. However, according to Effective Java, the second signature is preferred (as it is shorter and slightly clearer). In that book, the advice given is to use the second signature, and use a private helper method with the first signature if T is required in the method. Like this:

private <T extends Foo> void helper(Class<T> p_class) {
    // code
}

public void loadData(Class<? extends Foo> p_class) {
    helper(p_class);
}

Upvotes: 3

Related Questions