aspose file tools*
The moose likes Java in General and the fly likes Is use of reflection api encouraged? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Is use of reflection api encouraged?" Watch "Is use of reflection api encouraged?" New topic
Author

Is use of reflection api encouraged?

chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

Hi all, I am writing a web application. We are using spring 3.0. There are many forms in it. We have to validate each form. We are not using hibernate-validator which implements JSR330 specification. We are supposed to write a validator class for each and every form.

In each form all fields are mandatory. There are fields which take strings and fields which take integers, decimals etc. All forms have different validation rules.

All I want to do is write a class which takes a form object, lists all the methods in it. Invoke the getter methods, get the value, do basic validations like

Checking whether the entered integer-string is an actual integer
Checking whether the entered string is not alphanumeric
Checking whether the entered decimal-string is an actual floating point number
Checking whether the entered input does not contain all white spaces
and many more...

For this I wrote a class which exposes a single method to which takes the form bean and uses reflection api to validate. Everything is completed. I want to know whether using reflection api is encouraged in business applications or not.

I don't think this is a spring specific question. So I asked here.

Thank you all in advance, good day.


Love all, trust a few, do wrong to none.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

chaitanya karthikk wrote:I want to know whether using reflection api is encouraged in business applications or not.

Not by me. And here's just a few reasons:
1. It's unsafe - you can do virtually anything with reflection, and you lose all the normal compiler time checking provided by the language.
2. It's arcane - and somebody will have to deal with the code when you're gone. Glad it won't be me.
3. It's SLOW - up to 50 times slower than regular code.
4. (most of the time) It's unnecessary - very often it's done simply because the programmer can't be bothered (or doesn't understand how) to code a solution that doesn't involve reflection.

Your problem sounds like simple String validation to me; and reflection is the LAST thing I'd choose to do that - in fact it's the last thing I'd choose to do most things.

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
Richard Tookey
Ranch Hand

Joined: Aug 27, 2012
Posts: 1110
    
  10

Though I partially agree with Winston I don't 100% agree.

Many years ago I wrote a framework for doing pretty much what you are trying to do. It allowed one to build a map between a form field name and a (setter Method, validator, converter) triple. The user was unaware that behind the scenes reflection was being used. All the user had to do was to provide the name of the setter, the validator and the converter. Since the setter Method lookup was only done once for each field the whole was very very fast and very very effective. It was also very very easy to maintain since internally it was very very simple.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

Richard Tookey wrote:It allowed one to build a map between a form field name and a (setter Method, validator, converter) triple. The user was unaware that behind the scenes reflection was being used. All the user had to do was to provide the name of the setter, the validator and the converter. Since the setter Method lookup was only done once for each field the whole was very very fast and very very effective.

I have a couple of questions:
1. Was this done in Java?
2. How would the user know the name of a setter?

I have nothing particularly against keeping a map of field names and types - it seems a reasonably standard form of meta-data - but I'd expect it to be built by the application; and I'd probably implement the "validation" using an Enum. Furthermore, one of the things that chaitanya listed ("entered input does not contain all white spaces") strikes me as plain old vanilla String validation.

None of what I've heard so far suggests to me any need for reflection.

@chaitanya: Java is statically typed, and you throw that out at your peril. If you find yourself resorting to reflection code a lot, you should ask yourself two questions:
1. Do I need it?
2. Is Java the right language for this/me?

Winston
Richard Tookey
Ranch Hand

Joined: Aug 27, 2012
Posts: 1110
    
  10

Winston Gutkowski wrote:
1. Was this done in Java?

Yes.

2. How would the user know the name of a setter?


The user defined the Class that was to contain the form data and included in his servlet an instance of the framework object that mapped the field names to setter names. The framework class was thread safe and only one was constructed per Servlet. The converters and validators were a set of system wide classes created primarily by me in response to the Business requirements for the form fields and were also thread safe. The user just had to pass an instance of his class and the Servet request object to a method on the framework object.

The Business would not listen to some of our objections to some of the restrictions enforced by their requirements for form field syntax until one of the senior managers who lived in France found he could not register with the system because his French post code did not have the syntax of a British post code. From our point of view this was trivial to fix within the framework.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4490
    
    8

To be fair, I suspect many frameworks use reflection for this sort of thing. I'm thinking about those that use annotations to label model objects with certain validation criteria. I'm actually more familiar with the .NET frameworks, but I suspect some of the Java ones work in a similar way. For example, I can label a property as "Required", provide ranges for numeric data, provide regular expressions for string data, and write my own validation annotations for anything more complicated than comes out of the box. The framework then uses reflection to determine what rules to apply. This gives us declarative validation rules, which are actually much easier to maintain.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

Matthew Brown wrote:To be fair, I suspect many frameworks use reflection for this sort of thing. I'm thinking about those that use annotations to label model objects with certain validation criteria...

Now that makes a lot more sense, because at least then the rules are strictly defined. I imagine you could even use something like Guice; but chaitanya already said they weren't using dependency injection in his first post.

I also have to admit to an almost pathological loathing of reflection; mainly because I've seen it misused so much.

Winston
chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

Winston Gutkowski wrote:
chaitanya karthikk wrote:I want to know whether using reflection api is encouraged in business applications or not.

Not by me. And here's just a few reasons:
1. It's unsafe - you can do virtually anything with reflection, and you lose all the normal compiler time checking provided by the language.
2. It's arcane - and somebody will have to deal with the code when you're gone. Glad it won't be me.
3. It's SLOW - up to 50 times slower than regular code.
4. (most of the time) It's unnecessary - very often it's done simply because the programmer can't be bothered (or doesn't understand how) to code a solution that doesn't involve reflection.

Your problem sounds like simple String validation to me; and reflection is the LAST thing I'd choose to do that - in fact it's the last thing I'd choose to do most things.

Winston

Hi Winston, thanks for your valuable reply. Actually I know that misuse of reflection api causes serious issues. My TL actually asked me to do this way. I said him that the code will be hard to maintain. I also suggested him that this adds additional complexities for developers who maintain the code. I said that if use of reflection api for validation is a good approach, then why wouldn't frameworks like struts/spring provide such kind of apis which accepts any kind of object and do basic validations on it. But I could not explain him clearly.

Winston, can you please explain me this points clearly you lose all the normal compiler time checking provided by the language
chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

Winston Gutkowski wrote:
Matthew Brown wrote:To be fair, I suspect many frameworks use reflection for this sort of thing. I'm thinking about those that use annotations to label model objects with certain validation criteria...

Now that makes a lot more sense, because at least then the rules are strictly defined. I imagine you could even use something like Guice; but chaitanya already said they weren't using dependency injection in his first post.

I also have to admit to an almost pathological loathing of reflection; mainly because I've seen it misused so much.

Winston

@Winston: As Matthew said now a days all frameworks use reflection api extensively. I am working on spring framework and almost for all things spring used reflection api. When it comes to form binding, use of annotations etc. Then you shouldn't I use reflection api with careful and cautious coding?

I understand that frameworks which use reflection api, code according to standards like use of design patterns etc.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

chaitanya karthikk wrote:As Matthew said now a days all frameworks use reflection api extensively. I am working on spring framework and almost for all things spring used reflection api. When it comes to form binding, use of annotations etc.

There's a difference between 'use' and 'mandate'. I'm no Spring expert, but I expect that, like Hibernate (which I am familiar with), it uses reflection behind the scenes specifically to prevent you from having to deal with late binding - or, in the case of Hibernate, that monstrosity of a class called ResultSet.

Then you shouldn't I use reflection api with careful and cautious coding?

Well, as you can see, there's quite a spread of opinion, even from us experienced bods. Personally, I regard reflection as an aberration in Java, so I use it ONLY when I see no other choice, and when I do use it, I try to keep it to an absolute minimum.

Annotations are a bit different. Yes, they use reflective code, but the rules are much more clearly defined and their use is (hopefully) made clear by the Annotation itself; so I hope you document yours well.

Dependency injection is also a completely different kettle of fish as far as I'm concerned, and frameworks like Guice interest me a lot - again mainly because they save me from having to use reflection myself.

Hope that helps explain my views.

Winston
chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

@Winston: I want to write just one class which will do basic validations like checking whether the fields are empty, contains white spaces, names are alphanumeric, age, mobile numbers etc strings are integers, email fields contain valid email addresses etc.

Is there any specific approach to do this without using reflection api. I don't find any alternative.

I find only approach I find is write a single method whose argument list contains all possible fields.

Then if I want to validate login page I will pass username and password rest as null. Now the username can contain email or normal text. so I will have to use another another parameter which determines the content it can contain. So the validate method will have additional parameters.

For instance:But this way I will have to write lot of code and many if else conditions, hard to understand, maintain etc.

Can you please suggest some approach? Or I have to use individual validation classes to validate individual forms.
Jayesh A Lalwani
Bartender

Joined: Jan 17, 2008
Posts: 2447
    
  28

Spring does use reflection extensively, but at the same time, they are very smart about it. As someone mentioned earlier, Reflection is costly when method lookups are involved. Method calls are less costly. Spring does all lookups when it loads the beans. Since, most people use singleton, the beans are set to initialize at load time, so the only point you get a hit is during load time.

I have seen a homegrown DI injection framework that did all the reflection at runtime. Very slow and very messy. I have to ask:- why aren't you using Spring with Hibernate validator?. You are reinventing the wheel here
chaitanya karthikk
Ranch Hand

Joined: Sep 15, 2009
Posts: 806

Jayesh A Lalwani wrote:I have seen a homegrown DI injection framework that did all the reflection at runtime. Very slow and very messy. I have to ask:- why aren't you using Spring with Hibernate validator?. You are reinventing the wheel here
I know I am reinventing the wheel. I don't know why our architect does not want to use it. He says that why should I use an additional dependency. I already said that spring itself suggests to use JSR 330 implementation like hibernate-validator.
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 8414
    
  23

chaitanya karthikk wrote:@Winston: I want to write just one class which will do basic validations like checking whether the fields are empty, contains white spaces, names are alphanumeric, age, mobile numbers etc strings are integers, email fields contain valid email addresses etc.
Is there any specific approach to do this without using reflection api. I don't find any alternative.

Well, one way would be to use an Enum for your "types", which, as I said above, is probably how I'd look at it - at least for my 'first cut'.

Secondly - Separate type validation from non-specific stuff: "is a mobile number" is a completely different order of check from "is empty" or "contains whitespace".

Thirdly - Define what you want your "validator" to check for. An isValid(String) method sounds like a good start to me, but I suspect that you'll probably want to also include some of those more generic tests, maybe as static methods.

Fourth - You'll have to work out some stuff according to your needs. For example:
1. Is "Alphanumeric" a type? I'd say not, but you may think differently.
2. What is an "Age"? Is it a number of years? Or maybe current date/time - birth date/time? Is it human? Or geological?

The fact is that this is a web-page, so the chances are that all your source data is in String form. What you want to do is to get that translated into known Java types as fast as you possibly can. Presumably, whatever code is handling that page "knows" what it's supposed to get, so my approach would be to use that as my starting point and work from there.

What I wouldn't be trying to do is come up with a "generic web-page data handler"...At least, not yet.

Winston
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is use of reflection api encouraged?