jbsound jbsound - 2 years ago 103
Java Question

Java: Add a Class Property Dynamically

I'm relatively new to Java and have dug through the reflection capabilities, but for some reason can't figure out the following:

I need to get the String name of an instantiate class. Seems that I cannot find a way to do this with reflection, so I thought to add a class property dynamically that would contain the name of the class as a String.

How would I go about that?

Alternatively, I thought of creating a Public String property in the class that I assign the name of the instantiated class in the constructor. Didn't really figure out how to do that either.

Answer Source

If you want the name of a class as commented by Jorn Vernee you can use instance.getClass().getName()

Since you mention dynamically creating a string, I guess you may mean that you want the name of the object itself. The simplest way to get the object name is to construct the object and pass a name to the constructor to initialise a member string.

Something like

public class Enemy
    private String name;

    public Enemy(String name)
        this.name = name;
    public getName()
        return name;

Enemy orc = new Enemy("orc"); // could be an array of references instead of a var
orc.getName(); // returns the name of the object, obviously the name is whatever you construct the object with; so you could use any object identifier you like (such as a hash), this also means you can just construct the object and store its reference in an array 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download