SBmore SBmore - 7 months ago 48
Java Question

Generating a list of certain instance variables

I'm creating a program that writes data to a database. I've created classes for each table and I wanted the class to be able to create its own INSERT statement. Since the member variables will be the columns of the database I thought it would be a good idea to grab them with

and write them into an INSERT statement. I didn't want to duplicate code so I made a Table class that has a
and used that to extend the other classes.

The issue is that there could be other instance variables that I need in these classes (such as
) that I don't want to become part of the INSERT statement. I also want to assign values to the columns so I don't think I can just put them in an array without duplicating (so if I add a column I would also need to add it to the array).

Here is what I have at the moment, which will include the tableName in the INSERT query:

public class Table {
public String buildSqlInsertQuery(Object obj, String tableName) {
Field[] fields = obj.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
String[] placeholders = new String[fields.length];
String placeholder = "?";

for (int x = 0; x < fields.length; x += 1) {
fieldNames[x] = fields[x].getName();
placeholders[x] = placeholder;

return joinInsertQuery(tableName, fieldNames, placeholders);

private String joinInsertQuery(String tableName, String[] fieldNames, String[] placeholders) {
String query = "INSERT INTO " + tableName + " (";
query += StringUtils.join(fieldNames, ",");
query += ") VALUES (";
query += StringUtils.join(placeholders, ",");
query += ")";

return query;

public class Addresses extends Table {
private final static String tableName = "Addresses";
public String idCustomers;
public String address1;
public String address2;
public String address3;
public String city;
public String state;
public String zip;
public String country;

public Addresses() {
System.out.println(buildSqlInsertQuery(this, this.tableName));

Is there a way that I can flag certain instance variables that should be considered a column (such as with an annotation) or am I going about this completely wrong?


One way, which you have mentioned, is to use annotation to identify the instance variable as table name. Just define an annotation as this:

public @interface TableAnnotation {


And annotate the field having the name of the table with this:

public class Addresses {

private String tableName = "Addresses";
public String idCustomers;
public String address1;

Now in your Table class, use reflection (which you are already doing) to figure out the field with this particular annotation:

      System.out.println("This field " + field.getName() + " is the name of   table");