0

I am doing a Databases project and I'm connecting Java to a MySQL database.

After this, a colleague of mine has to connect Java to a server and, trying to make his job easier I'm attempting to transform the ResultSet the database returns to JSON myself.

I'm using the JsonSimple 1.1 API and I'm trying to avoid creating tons of methods for each database table. My idea is trying to create a method that would transform anything it gets to JSON with correct types and names. This is my code:

(...)                                                                    
ResultSet resultSet = statement.executeQuery();
ResultSetMetaData rsmd = resultset.getMetaData();

// Treat the results and tranform to JSON.
while(resultset.next())
{
    Class<?> objectClass;
    JSONObject obj = new JSONObject();

    for (int i=1; i <= rsmd.getColumnCount(); i++) {
        objectClass = SQLTypeMap.toClass(rsmd.getColumnType(i));

        // This is what I thought would work. As you can guess, it doesn't. 
        obj.put(rsmd.getColumnName(i), new objectClass(resultset.getString(i)));
    }
    result.add(obj);
(...)

SQLTypeMap is a class I created that maps SQL Types to Java Classes and returns the class itself.

My question is simple: is there any way I can instantiate a new Java Class without knowing its type before runtime? If so, how?

Thank you.

  • Read about the reflection API, then check the javadocs of `Class.newInstance` – ernest_k Apr 20 '18 at 13:59
  • I think this will help you https://stackoverflow.com/questions/6514876/most-efficient-conversion-of-resultset-to-json – cheffe Apr 20 '18 at 14:06

0 Answers0