Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using reflection

Status
Not open for further replies.

nirajj

Programmer
Mar 12, 2003
103
US
Hello everybody!

I have never used reflection before is my first time even playing around with it.

I was thinking about a utility that will take a pojo as a parameter and them split a delimited line based on the fields defined in the pojo, create a new instance of the pojo and set the fields.

The idea is to parse a delimited file and not having to write the parsing logic every time. Just create the object that matches all the columns in the file and you are good to go.

I am using reflection to achieve this. However, I have never used it and I am not sure of any side effects when it comes to performance? Or any other thing I should be aware of.

Please advice.

Thanks!
 
Reflection has a very poor perfomance, it's difficult to code and more difficult to maintain. Furthermore, it breaks complelety the OO design and has to take into account security constraints.

I would avoid it.

Cheers,
Dian
 
Hi Diancecht,

Thanks for the reply.

I did fear the performance issue.

However, as far as coding goes, I am already done with it and I have tested it as well. Seems to work really well.

Its a really basic utility. All it does is:
1. Look up the class, create a new instance of the class.
2. Look up all the instance fields in the class and set the value
3. Return the new object.

 
I've used it myself several times and I know it works and offers a solution for some situations, but I have to discourage its use for the reasons I provided.

Reflection is one of those things you shouldn't do but sometimes a programmer has to do what a programmer has to do.

In your case, I can't tell if there's an OO design without further details. How can you know the values for the fields? Won't an key-vaule structure do the job?

Cheers,
Dian
 
nirajj,

Any time you are doing dynamic class loading, reflection is key.

Some things you can do to avoid performance hits, but would make your class more static:
1. Use select case statements, and allow only predefined class types. Ex:
switch (type) {
case typeInt: // code, etc
case typeInteger:
case typeString:
case typeDate:
case typeObject:
}

2. Try to make a good abstract class for what data you are trying to interpret, so that you can always call "toString()" or "getValue()" or similar.

I've noticed reflection is essential for certain scalable tasks. I've even used it to call functions only available in newer framework when locked into compiling against old framework (sounds stupid, but it works).

-Tres
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top