phuoc pham
phuoc pham

Reputation: 13

Is this impossible get name of class and set for variable inside class?

When I create:

player huhu = new player();

I want to get "huhu" to String name inside player;

public class player{
    String name = ??? How to get "huhu" here?
    ....
}

Sorry for my poor english!

Upvotes: 1

Views: 55

Answers (2)

Isaac
Isaac

Reputation: 16736

No, you can't access the local variables' names using standard Java.

If you really need access to the name, you'll have to pass it as a constructor parameter, as specified in some of the comments. That would require you, however, to change your code to support this for each and every variable you declare.

I'm seriously scared to ask why you need this functionality.

Upvotes: 1

jahroy
jahroy

Reputation: 22692

class Player {
    private String name;

    public Player(String s) {
        name = s;
    }
}

Player huhu = new Player("huhu");

Notice that I'm capitalizing the name of the class.

You should always capitalize your class names.

Upvotes: 2

Related Questions