0

I have created different classes with it's variables and I'm trying to create a Java program that creates tables in a SQL database. The issue is that I don't know how to send a class as a parameter in a function.

I'm working on this function:

public void createTable (/*Class c ?*/) {

    ArrayList<String> fields = new ArrayList<>();

    for (Field f: c.class.getDeclaredFields()) {

         fields.add(f.getName());
    }

    Statement statement;

    statement = connection.createStatement();    //This part of the function wouldn't work. But let's focus on the question
    statement.execute("insert into " + c.getSimpleName() + "(" + String.join(", ", fields) + ") values" etc...
}

Please note that the second part of the function where I want to insert data into SQL database would not work as it's not finished. But, how could I receive in this function different classes (with different variables obviously) and do the same for all of the classes? (create a list with the name of it's fields).

user157629
  • 624
  • 4
  • 17
  • 1
    checkout this this question [How do I pass a class as a parameter in Java?](https://stackoverflow.com/questions/4872978/how-do-i-pass-a-class-as-a-parameter-in-java) – SwissCodeMen Mar 25 '20 at 21:56
  • Do you want to pass a class, or an instance of that class (an object)? As you're generating an insert statement, I assume you also want to pass values, in which case you need an object, not a class. Also, please learn about prepared statements. You should not concatenate values into your query string, that makes them vulnerable to SQL injection. And finally, consider looking into ORMs like Hibernate: you're reinventing the wheel (and badly). – Mark Rotteveel Mar 26 '20 at 08:42

2 Answers2

0

This is simple just refactor as the following:

public void createTable (Class c) {

    ArrayList<String> fields = new ArrayList<>();

    for (Field f: c.getDeclaredFields()) {

         fields.add(f.getName());
    }

    Statement statement;

    statement = connection.createStatement();    //This part of the function wouldn't work. But let's focus on the question
    statement.execute("insert into " + c.getSimpleName() + "(" + String.join(", ", fields) + ") values" etc...
}
Harry Coder
  • 2,429
  • 2
  • 28
  • 32
user3359139
  • 430
  • 4
  • 17
0

For any person looking an answer in this question, this worked for me:

public void createTable (Class c) {

ArrayList<String> fields = new ArrayList<>();

Object ob = c.newInstance();    

for (Field f: ob.getClass().getDeclaredFields()) {

     fields.add(f.getName());
}

// etc...

}

user157629
  • 624
  • 4
  • 17