Is there any way that I can take a String and somehow use it as if its the name of one of my declared Objects? For example, if I have an Animal named germanShephard, is there some way I could say String gerSh = "germanShephard"; and then treat gerSh as if it was the equivalent of saying germanShephard in my program?

Beforehand I'm sorry for my English...
I don't know any way to dynamically create variable, but I can offer some alternatives:
1. Use Dictionary
2. Create class variable dynamicly

Java doesn't support creating variable names dynamically.

Is there any way that I can take a String and somehow use it as if its the name of one of my declared Objects? For example, if I have an Animal named germanShephard, is there some way I could say String gerSh = "germanShephard"; and then treat gerSh as if it was the equivalent of saying germanShephard in my program?

Use either TreeMap or HashMap

Dictionary is also an okay way to go, but I believe it is a deprecated API (or incredibly outdated).

Edit: Actually, you can probably get away with using a Pair<K, V> instead of something that handles an entire collection.

I'm not sure where it is defined in the Java Standard Library, but if all else fails you can easily create your own pair class.

> For example, if I have an Animal named germanShephard, is there some way I could say
> String gerSh = "germanShephard"; and then treat gerSh as if it was the equivalent of
> saying germanShephard in my program?

You can't because gerSh is now a String. The closest you can come to this kind of name to Object mapping is by using a Map or by using the reflection API, which again doesn't work for `private' members.

The behavior you speak of can be seen in all ECMAScript implementations. Something of the sort:

var obj = {dog: {name: "poo boy", type: "poodle"},
                cat: {name: "neko san", type: "siamese"}};
var key = "dog";
alert(obj.dog.type); // poodle
alert(obj[key].type); // poodle

I've used reflection before but I don't understand how it helps solve my problem. It just lets me know about certain properties of an Object, such as its classname. The concept of a Map is somewhat familiar, but it doesn't help avoid the work, does it? The primary reason I'd want to do this is b/c it'd be less work. For example, if I had 200 buttons, button1-button200, it'd be useful if I could do what I described in my first post. I guess this isn't possible in Java though.

If you have two hundred buttons you should store them in an array.

I agree, but that isn't what I asked. Anyway, thanks for your help everybody. If anyone knows any languages where you can do this, please let me know, with a code example if you would. Otherwise consider this topic closed.

I still don't understand the question entirely, but in many scripting languages you can evaluate any given string as if it were code.

Example in Ruby:

var = "Hello, world!"
puts var # prints: Hello, world!

var2 = "var"
puts eval(var2) # prints: Hello, world!

Anyway, except when metaprogramming, this technique should be used very sparingly. There aren't many good reasons to do this.

And sorry if I misinterpreted your question.

I think you answered my question correctly in your first post. I was just asking if it is possible to save a value into a String, then use that String as if it was the name of an Object (rather than being a String).

So, for example, if I had a String buttonName = "button1"; then I was asking if I could do

buttonName.whatever(), and have buttonName evaluate itself to see whether or not there was an Object named "button1" in the program. If so, it would call whatever().

Now obviously, this doesn't work as I wrote it, since Java treats buttonName as a String (as it should). I was just asking if there were any techniques that would do what I described above.

Then I was correct in my last response.

Again, in Ruby, what you just described would look like this:

button_name = "button1"
eval(button_name).whatever # calls whatever() on the variable button1

> It just lets me know about certain properties of an Object, such as its classname

It does much more than that.

> The concept of a Map is somewhat familiar, but it doesn't help avoid the work, does it?

It provides a solution to your problem. IMO, what you are looking for is not a solution but a syntactic sugary way of doing things. Like previously mentioned, either use an array, a map or a JVM targeted scripting language like maybe Groovy, Scala, Rhino etc.

> I guess this isn't possible in Java though.

Yes, in the same way it isn't possible to create classes in C.

I don't know all that much on reflection, but I have used it before. I don't see how it is useful. I've seen plenty of examples of reflection, so I understand how it is used. Just not why. Can anyone provide a reasonable example of a situation that needs reflection and a short explanation of why? All the tutorials I see give examples of reflection, but they are never situations where reflection is necessary. For example, I saw reflection being used to print out hello world. Pointless.

Think of all the frameworks which let you specify your custom class in their configuration file and load those classes at runtime. The servlet specification for instance has a deployment descriptor which allows the developer to configure servlets, filters for his application. All the developer has to do is to specify the class name and the required processing is done at runtime by the container.

Also look into Spring or Guice which are IOC/Dependency Injection frameworks.

That being said, there *are* a lot of uses of reflection; it's just that they aren't that obvious.

If you make your object Serializable then you can store information about the object in String form. It won't be as readable as "germanShepard" but you could store objects serials somewhere to enter. Doesn't sound too practical.
Another thing you can do is make a factory class. The class would take certain strings and generate objects for you to use based on that string name. It's a common design pattern and I've seen it used while poking around with code at work.

If you make your object Serializable then you can store information about the object in String form. It won't be as readable as "germanShepard" but you could store objects serials somewhere to enter. Doesn't sound too practical.
Another thing you can do is make a factory class. The class would take certain strings and generate objects for you to use based on that string name. It's a common design pattern and I've seen it used while poking around with code at work.

s.o.s, no offense, but sifting through a ton of material to *maybe* answer my question doesn't sound too appealing. If reflection is indeed useful, there have to be some practical, simple explanations of why this is the case.

bionic: Making objects Serializable means you can write the objects to file in Binary form and read them back in this way, so that you can store and retrieve your Objects more easily than if you were to do text input and output. Maybe I misunderstood what you said, but it's actually much more practical than reading/writing Strings to a file.

Regarding your other point, you can also take Strings and make objects by using a simple if statement, so I don't see why that would be a good use of reflection.

> Can anyone provide a reasonable example of a situation that needs reflection and a short explanation of why?

We use it on our current project for dynamic configuration of our UI. All panel components share an interface and with a simple XML file we can reconfigure the frames and panels with no change to the compiled jar file. We also use it for our reporting engine to load column classes that can be plugged in to our table-based reports. These are simple usages of loading classes that share a common interface by supplying their class name and other properties in simple xml files.

Reflection is a very specialized solution, much like the Java Native Interface, Remote-Method Invocation, Wildcards, Design Patterns, transient values, volatile values, concurrency, etc.

Don't expect simple solutions for something that is seemingly "simple."

BestJew: Yeah, I meant an if statement. Reflection is probably overkill for your stated requirements.

> Can anyone provide a reasonable example of a situation that needs reflection and a short explanation of why?

We use it on our current project for dynamic configuration of our UI. All panel components share an interface and with a simple XML file we can reconfigure the frames and panels with no change to the compiled jar file. We also use it for our reporting engine to load column classes that can be plugged in to our table-based reports. These are simple usages of loading classes that share a common interface by supplying their class name and other properties in simple xml files.

I've reflection to make method calls on auto-generated DAO objects that were based on similar tables in my data base. There are good uses for reflection, but most of the time you can get by without using it.

> Can anyone provide a reasonable example of a situation that needs reflection and a short explanation of why?

We use it on our current project for dynamic configuration of our UI. All panel components share an interface and with a simple XML file we can reconfigure the frames and panels with no change to the compiled jar file. We also use it for our reporting engine to load column classes that can be plugged in to our table-based reports. These are simple usages of loading classes that share a common interface by supplying their class name and other properties in simple xml files.

Can you elaborate somewhat on the first example? Do you mean that depending on what the contents are of the XML file, different panels would appear which are created from classes that have their own content... but that the type and size of the panel are always the same? Because I don't see how you could use different sized panels each time, that would mess up the layout. Unless, I suppose, you somehow dynamically figure out how big each panel was and did calculations based on that also. The second example seems to make sense - you have a table and its layout set ahead of time, and based on what Strings are input, that table looks up the classnames (presumably each String represents a classname?) then fills the table with each of those classes, treating a class as a 'column'? That example seems to make sense, because if you wanted to be able to put anything in the table without recompiling, I guess reflection would be the only way to do that.

Can you elaborate somewhat on the first example? The second example seems to make sense - you have a table and its layout set ahead of time, and based on what Strings are input, that table looks up the classnames (presumably each String represents a classname?) then fills the table with each of those classes, treating a class as a 'column'?

You're sort of right. The classes I was mentioning were generated by crawling throught the DB and writing java code off of the table information. It was really sweet. It didn't use reflection though. It queried the database for metadata.
Reflection is used for calling methods, not class creation. So my DAO (data access object) class would have methods like: getUserId, getCurrentDTTM, etc. And I could call these methods using string literals ("getUserId", "getCurrentDTTM") from the code. Normally you'd use an interface for that kind of work, but since the DAO objects are auto generated, we used reflection

In the example Ezzaral gave, if he is using a different panel based on whats in the file, he would have to create an Object of the class that represented his panel. So how is it that reflection isn't used to create classes (I'm assuming you meant create objects, not create classes)?

Do you mean that depending on what the contents are of the XML file, different panels would appear which are created from classes that have their own content... but that the type and size of the panel are always the same? Because I don't see how you could use different sized panels each time, that would mess up the layout.

Layout and/or size are nothing more than attributes that you can put in an xml descriptor like any other property. We place one or more panels in a frame, with whatever attributes are required. The only part that needs reflection at all is the instantiation of a class by name with a specific constructor and the specification of the constructor parameters.

s.o.s, no offense, but sifting through a ton of material to *maybe* answer my question doesn't sound too appealing. If reflection is indeed useful, there have to be some practical, simple explanations of why this is the case.

It seems as though you missed my entire post. The first two paragraphs of my previous post mention the most widely used implementations of the reflection API. Another use of the reflection API is to implement the Webservice client for SOAP type web services wherein the XML response from the server is converted to an object tree using the schema definitions.

What I was saying is that I don't understand most of that terminology, so the point alone has no impact. I hope I wasn't rude - I wasn't trying to be.

What I was saying is that I don't understand most of that terminology, so the point alone has no impact. I hope I wasn't rude - I wasn't trying to be.

If you work in an environment similar to mine, you'll have people telling you to "GIYF!" quite a bit XD.

If there is a term you don't understand, you should definitely study it. I find it much easier to learn programming concepts after educating myself with terminology.

Not only that, but by understanding more terminology, you can come up with more meaningful definitions for words in code that you are planning to share with others that may work with you or will be the receiver of an implementation you designed when you hand off the code.

Wikipedia, Google and Dictionary are your ultimate programming friends, to say the least! O_O

Point taken, but my point was that a combination of unknown phrases adds a lot of ambiguity which makes it difficult to simply do a google search, combine definitions, then come to an understanding. It makes a lot more sense to explain things with some sort of clarity to begin with. And thats not a slight at s.o.s - he has definitely helped me in the past, and is overall a very helpful guy on this site. I'm just saying that its not out of laziness that I don't look those terms up -- its for the same reason that I wouldn't read a passage out of a French 300 textbook if I only knew basic sentences. It would take hours, maybe months, of work just to understand that passage. But maybe I shouldn't be taking the class in the first place. . or asking questions about reflection and expecting fairly simple answers. Lol. And yes, this analogy sucks. It could be applied in 100000 different ways.

What I was saying is that I don't understand most of that terminology, so the point alone has no impact. I hope I wasn't rude - I wasn't trying to be.

It would be difficult to explain the real use of reflection without throwing in a lot of terminology. Maybe reading this article will help you understand how reflection changes the way we think of object construction/instantiation and how the concept of reflection benefits the real world software development.

commented: Good reference. +15
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.