0

In Java, when I get a ResultSet I made a method that would map that to a specified class. It more or less looks like this:

public <T> T mapRow(ResultSet results, Class<T> type) {

So, when I actually call the class, it looks like this:

mapRow(results, Row.class);

Please help me understand this conceptually.

  1. Why can I not just do something like mapRow<Row>(results);?
  2. Also, the current way I'm invoking mapRow, is there an implied <Row> before the method call?
tau
  • 6,499
  • 10
  • 37
  • 60

2 Answers2

3

You can call:

object.<Row>mapRow(results, Row.class);

but you still need the second parameter anyway, you cannot remove it for what you are trying to do.

This is because there is no way to know the type of T at runtime when mapRow is called, due to generics erasure.

Community
  • 1
  • 1
Angular University
  • 42,341
  • 15
  • 74
  • 81
2

the current way I'm invoking mapRow, is there an implied before the method call?

The point of the <T> T mapRow() declaration is that T is inferred from the method arguments or the LHS type to which the result is being assigned. In your case, you pass in a class object which serves to infer the return type.

The above is only one half of the purpose of the class argument, the second part being reflection: mapRow will call newInstance() on it to create the object to return.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • yes, that is correct. could you please define LHS for me? thanks! – tau Apr 18 '14 at 19:44
  • 1
    Left-Hand Side of an assignment expression. – Marko Topolnik Apr 18 '14 at 19:45
  • ah okay. i understand how the type could be inferred from that. how could the type be inferred from the method arguments? like what if i passed in more than one class object? – tau Apr 18 '14 at 19:46
  • 1
    If the method signature says ` T mapRow(Class c1, Class c2)` then you won't be allowed to pass in two different class objects. – Marko Topolnik Apr 18 '14 at 19:51