Forums Register Login

How to call methods with indexes

+Pie Number of slices to send: Send
I have lots of methods, which are almost the same, apart from the object name and the name of setters and getters.
What I would like to achieve is:

fill_DocLine(ResultSet rs, DocLine, [Index method, Input value ...
fill_DocLine(ResultSet rs, DocLine, [3, rs.getInt(1)], [4, rs.getString(2)], 6, rs.getInt(3)] ) {

DocLine refers to the Java Object to fill, and 3,4,6 refers to the indexes of the methods

DocLine line = new DocLine();
line.setNo(rs.getInt(1)); //method index 3 = setNo
line.setText(rs.getString(2)); //method index 4 = setText
line.setType(rs.getInt(3)); //method index 6 = setType

I heard of reflection, can I achieve this with reflection, if so how.
+Pie Number of slices to send: Send
Hi Renè,

IMHO the main flaw with your approach is that you need indexing your set methods, because Java reflection doesn't keep any order by itself on declared methods
or fields of a class. Moreover, you need to keep in sync ordering of the columns in the query with ordering of the setter methods: what about if instead of
"SELECT ALFA, BETA FROM TABLE " you run a "SELECT GAMMA, ALFA, BETA FROM TABLE " ?

You may try and write a custom annotation which let you to map a field of your DocLine class with a column of the select, for example



After getting a ResultSet from your query, you may want to use ResultSetMetaData and get retrieved columns' names, and follow a similar pseudo-code



Of course an heavy usage of reflection causes the code to run slower, but it may be a first step towards reading cursors
automatically instead of writing boilerplate code.

By the way: this it's just the role played by Persistence Engines like JPA or Hibernate: they do something similar of what
I described you, but, of course, in a smarted and cleverer way... but if you want to play with JDBC that may be an interesting starting point.



It's a tiny ad only because the water is so cold.
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 454 times.
Similar Threads
Fill java.awt.Choice from a List generated by a resultSet
Something wrong with the PreparedStatement
how to improve my program code ?
SQL Exception Invalid Descriptor Index
How to retrieve the first record in a database table
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:04:45.