1

So what I'm wondering is if it's possible to make a generic Postgresql connection class where you could pass as a parameter the object type you'll want to read from the DB (as a string) and then actually read from DB and return the proper List of objects.

Something like:

class DbConnection{ 
    string type;

    public DbConnection(string objectType) {
        type = objectType;
    }

    public getConnection() {..}

    public List<Object> readObjectsDb() {
        ...
        return List<type> theObjects // type is the atually class type, no longer the string now
    }
}

Basically I'd be able to read from any Postgresql db with this class based on an input parameter, and knowing that the type I'm passing actually exists in my program.

Is it possible? Maybe with reflection somehow?

5
  • There are many libraries that will do this for you. Spring's JdbcTemplate for example. Commented Jan 1, 2017 at 21:16
  • Looks good, I still don't understand how passing my type as a string would work in transforming the object list into the specific type I want it to be Commented Jan 1, 2017 at 21:25
  • The query method accepts a RowMapper. Write you own or use the built in BeanPropertyRowMapper. Commented Jan 1, 2017 at 21:29
  • You may find the responses to this old question useful. Commented Jan 1, 2017 at 21:40
  • This is iffy. If your return type is List<Object> what's the benefit of discovering the type? You'll lose that info instantly anyway. Why not just accept a Class<T> instead of the string name, get the name like clazz.getSimpleName() or whatever, and return List<T>? Commented Jan 5, 2017 at 0:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.