Getting static member from Field

Hello,

I have a 'static type safe enum class' and I want to use reflection to implement its toString() method, the String returned should be the name of the field.

(Note that the static instance variables themselves do not have String fields that could be used for the toString() return value.)

I am able to iterate through all fields of the class and print out the names using getName()

But not sure how to compare the types of the fields to a particular type. For example:

for (int i = 0; i < fields.length; i++)

{

Field field = fields;

// how to compare a field to know if it is a

// particular static instance field

if (field.getType().equals(MyEnum.A_STATIC_INSTANCE))

{

return field.getName();

}

}

[808 byte] By [tedhilla] at [2007-10-2 20:14:28]
# 1

for (int i = 0; i < fields.length; i++)

{

Field field = fields[i];

Object fieldValue = field.get(null);

if (fieldValue == this) return field.getName();

}

throw new IllegalStateException();

Note that [code] tags produce the pretty formatting in this post.

YAT_Archivista at 2007-7-13 22:56:39 > top of Java-index,Core,Core APIs...