• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About sqEmp.<Integer>get("id") in chapter 9 of JPA Pro 2

 
Himai Minh
Ranch Hand
Posts: 1360
7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In chapter 9 of JPA Pro 2 , there is a code like this:


Is this a Java 8 new feature spEmp.<Integer>get("id) ? I have not yet seen a method call with a generic type in front.
What is that<Integer> mean? Does it mean that get ("id") takes an integer as a parameter?
 
Stephan van Hulst
Bartender
Pie
Posts: 6503
83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, this has been around since Java 5. You have to do this when the compiler can't infer the type argument of the method call.

In this example, sqEmp.get("id") would return a Path<Object>, because the compiler doesn't have enough information to know that you want a Path<Integer>.

If the get() method had accepted a second parameter of type Class, you could have done this instead:

The compiler would then know what type argument to pass to the method call, and you wouldn't have to do it explicitly using the strange notation.
 
Stephan van Hulst
Bartender
Pie
Posts: 6503
83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You also don't have to explicitly pass the type argument if you assign the result to a variable first. That way the compiler can also infer the type:
 
Himai Minh
Ranch Hand
Posts: 1360
7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Stephen, thanks for the information.
It is a "rare facility of Java generics" according to this https://www.ibm.com/developerworks/library/j-typesafejpa/


The weakly typed API, however, cannot return correct generically typed expressions, thereby generating a compiler warning for an unchecked cast. One way to get rid of these pesky warning messages is to use a relatively rare facility of Java generics: parameterized method invocation, as shown in Listing 19's invocation of the get() method to obtain a path expression.

 
Stephan van Hulst
Bartender
Pie
Posts: 6503
83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the example code they use, it's not necessary because the compiler can infer the generic method type argument from the variable the result is assigned to:

This shows you that this facility is actually even more rare than they say.

If you find that you have to write code that has to pass type arguments explicitly, the API is probably not well-designed.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic