0

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.

Shaun Wild
  • 1,237
  • 3
  • 17
  • 34

1 Answers1

3

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

Alexander
  • 1,332
  • 10
  • 17
  • This was my initial idea, I just thought I'd see if there was a way to get ahold of the fieldName. This will have to suffice for now however. Thanks. – Shaun Wild Oct 26 '13 at 13:59
  • 1
    I agree. According to this (http://stackoverflow.com/questions/744226/java-reflection-how-to-get-the-name-of-a-variable), getting a the variable name of a class instance is impossible in Java. – Vincent Vieira Oct 26 '13 at 14:00
  • Jet a conventional OO-application should not have to use reflection in my opinion. – Alexander Oct 26 '13 at 14:03
  • You can get the names of variables in a given instance (or static) through reflection, but you would have to program your own way to translate a *reference* to a variable into that name. Putting the name in the class is at least 20 times easier. – arcy Oct 26 '13 at 14:04