Reputation: 57
I am trying to make a restful api for logistics query.
It accept two paramsmeters: shipping_id and tracking_number, and it will call a third-party api to get the result and do something with it.
there are tens of third-party apis provided by different companies, and which to call depends on the value of shipping_id.
my solution is like this:
there will be a superclass 'LogisticsQueryController'
and many subclasses:
'ALogisticsQueryController','BLogisticsQueryController'...extends 'LogisticsQueryController'.
and keep a map ('shipping_id'=>'class_dir').
With shipping_id given, I can get a class_dir by shipping_id, and then new an instance using reflection.
But I heard reflection in Java could be inefficient, so what is the better solution?
Upvotes: 2
Views: 100
Reputation: 140525
In general, reflection is of course "more expensive" than "ordinary" bytecode.
But keep in mind: you are already talking about a "network facing" interface.
So even when that usage of reflection adds 10 ms to your overall response time, that penalty might be acceptable - assuming that it helps you to create a clean, maintenable architecture that is easy to extend;for example when you have to add other 3rd party libraries in the future.
Thus the answer is: first measure if your intended usage of reflection has any significant impact on performance in the first place. And then assess if using reflection really helps with the over quality of your architecture.
On the other hand: couldn't you simply create a factory interface, and many different implementations of that interface, that know how to create the required objects without using reflection? And then you simply put instances of those factories into your map.
Upvotes: 1
Reputation: 2265
Yes Reflection is inefficent. I couldn't see any reason of using reflection in your scenario. What about implementing a factory design pattern to get a new instance of your specific implmentaiton for every shipping_id through your static factory method.
Upvotes: 2