kumarD
kumarD

Reputation: 594

Creating java objects based on their type

I have a set of data objects, which correspond to rows in RDMS table, as in ClassA -> Rows of TableA ClassB -> Rows of TableB . . . ClassZ -> Rows of TableZ I am fetching these records using JDBC and creating objects from the result set(Please note that the result set can be huge) I have custom parsers for each class i.e parseClassA(), parseClassB()....parseClassZ(), currently i am having a function with a huge switch statement which determines the type of the class like switch(classType) and gives me an object of the corresponding class, i want to eliminate this switch statement, which is the optimal way to do this?

Upvotes: 0

Views: 75

Answers (2)

Christian Bongiorno
Christian Bongiorno

Reputation: 5648

This is called an ORM - hibernate is far-and-away the most widely adopted. Or, you could opt for a DSL. However, since we are on the subject, and we might want to have a functional looking approach here are the outlines:

Stream.of(resultSet).flatMap(r -> someHowMakThisAStream(r))

But, you're lookup map should be of type

Map<String,Function<Map<String,Object>,T> lookup...
lookup.put("SomeTable", SomeClass::new);

You will want each class to take a Map of column names to values (normalizing) and not the resultset directly so that each instantiation can't accidentally forward the resultset too far.

Then you can, in psuedo functional, do: stream.of(results).flatMap().map(valMap -> lookup.get(tableName).apply(valMap))

Upvotes: 2

davidxxx
davidxxx

Reputation: 131326

You could use a map structure that associates the class to create to the parser to create it :

Map<Class<?> clazz, Supplier<Parser>>

You could initialize the map with all required mappings :

 static{
    parserByClass = new HashMap<>();
    parserByClass.put(MyClass.class, MyParserMyClass::new);
    parserByClass.put(MyOtherClass.class, MyOtherParserMyClass::new);
    ...
 }

When you need to create a specific class, you could use the map to retrieve the parser of this class:

Parser<MyClass> parser = parserByClass.get(MyClass.class).get();

You can so call the parse() method of the parser :

ResultSet resultSet = ...;
MyClass parse = parser.parse(resultSet);

Ideally, you should have a Parser interface to define the parse() method and to allow to define the returned type :

 public interface Parser<T> {   
   T parse(ResultSet resultSet);    
 }

Please note that it is a untested code.

Upvotes: 1

Related Questions