• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to call methods with indexes  RSS feed

René van der ven
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Claude Moore
Ranch Hand
Posts: 894
IBM DB2 Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

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.

  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!