Shaun Wild
Shaun Wild

Reputation: 1243

How to get the field name of a variable?

I've got some final static Road's declared like so:

public static final Road street = new Road().setWidth(20).setRoadColour(0xAAAAAA).setRoadLengths(500, 100).setDiversity(0);
public static final Road junction = new Road().setWidth(60).setRoadColour(0x999999).setCustomGenerator(new JunctionGenerator());
public static final Road normalRoad = new Road().setWidth(30).setRoadColour(0x999999).setRoadLengths(1000, 2000).setDiversity(2).setChanceForTurn(0).setRoadChance(street, 1);
public static final Road motorway = new Road().setWidth(60).setRoadColour(0x0000FF).setRoadLengths(1000, 100000).setDiversity(1).setChanceForTurn(0).setRoadChance(normalRoad, 1);

And i want to be able to fetch the name of the road by it's instance, e.g-

I was thinking the method would be something along these lines

Road.street.getClass().fieldName();

And that will return the name of the field I declared it with.

Upvotes: 0

Views: 78

Answers (1)

Alexander
Alexander

Reputation: 1382

Give your Road-class a private String roadname and a getter, it would be the the conventional way to do it.

Upvotes: 3

Related Questions