File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes java reflection - flyweight pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java reflection - flyweight pattern" Watch "java reflection - flyweight pattern" New topic

java reflection - flyweight pattern

Anamitra Bhattacharyya

Joined: May 20, 2002
Posts: 5
Hi All
I am a bit surprised to see that in the java reflection package - none of the api utilize this flyweight pattern. If I see the getDeclaredMethod api I would assume that everytime the same Method object should be returned if the signature is same. But surprisingly everytime a different Method instance is returned - though they all point to the same method. Does anyone have any idea why its designed that way - rather why there is no caching of the Method instances?
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Caching is a gamble that the cost of memory to hold the cache is less than the cost of object creation. (Cost being overall negative impact on how the program runs.) Apparently the designers didn't want to make that bet. If somebody asks for a zillion different methods a cache will chew up memory and deliver no value. If somebody asks for the same method a zillion times, I guess they'll soon figure out they need a cache and write one. Did that make sense?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Anamitra Bhattacharyya

Joined: May 20, 2002
Posts: 5
I do get your point - but see the case of String objects - they are pooled by the java runtime itself. So I was not sure whether its just "not my responsibilty" approach or there was some real technical reason behind not implementing the cache in the reflection api - like dydnamic classloading etc.
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The JVM pools only some string objects -- those that it itself needs to pool to ensure specific guarantees made by the Java language. It doesn't pool all strings.
A similar argument that comes up from time to time: calculating hashCode() for a String is an expensive operation. Why not cache the result? The answer used to be that, while that would speed up some software, it would penalize everybody by occupying more space per string.
Eventually, somebody changed their mind, because nowadays String does cache the hashCode value.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: java reflection - flyweight pattern
It's not a secret anymore!