1

I want to make something like this. How I can do this pretty in java with generics?

 public <T [Integer or String]> Float getFloat(<T> column) throws SQLException{
    Float result;

    try {
        result = ResultSet.getFloat(column);
    } catch (NullPointerException e) {
        result = null;
    }
    return result;
}

Now my code looks like this:

public Float getFloat(String column) throws SQLException{
    Float result;

    try {
        result = rs.getFloat(column);
    } catch (NullPointerException e) {
        result = null;
    }
    return result;
}
public Float getFloat(int column) throws SQLException{
    Float result;
    try {
        result = rs.getFloat(column);
    } catch (NullPointerException e) {
        result = null;
    }
    return result;
}

I do this because method rs.getFloat() may receive String (Column label) & Integer (Column Index) only. But this not important for my method.

Bogdan Samondros
  • 138
  • 1
  • 10
  • It would be possible to use lambdas: `public Float getFloat(Function function, T t) ` but because of JDBC's checked exceptions it won't be much fun to do that, – user140547 Jun 10 '16 at 12:19

1 Answers1

0

This doesn't seem like a good use case for generics, IMO. Both String and Integer are final classes so there are only 2 possibilities here. Seems like it would just be easier to overload the method.

You can bound a generic like <T extends A & B> but I have found no capability to use | operator for this kind of bounding.

micker
  • 878
  • 6
  • 13