Take the 2-minute tour ×

Sample not working :

Class<?> c = o.getClass();

Field f = c.getDeclaredField("myColor");

String valueOfMyColor = (String) f.get(o);

The problem in this code is that you have to cast with the String class. What I'm looking for, is to be able to find the class of an attribute from its name.

For example :

class Brush {
    Color myColor;

//Somewhere else, in a far far away galaxy
Class<?> c = getMyClassFromAttributeName("myColor");
// and c should be of type Color

I've tried

Field f = this.getClass().getDeclaredField(code);
Class<?> c1 = f.getClass(); //Gives Field 
Class<?> c2 = f.getDeclaringClass(); //Gives Brush

Thanks !

PS: Used sample code from In Java, how to get attribute given the string with its name?

share|improve this question
add comment

3 Answers

up vote 1 down vote accepted

Use Field.getType();.


Class<?> fieldType = f.getType(); //Should return Color.
share|improve this answer
And then how would you be able to modify it in the current object ? –  Camille R Nov 29 '11 at 15:38
@Camille R, I don't follow, please elaborate. –  Buhake Sindi Nov 30 '11 at 6:53
I was looking for a way to be able to modify the field from an "abstract" Field. and I finally found ((Color)f.get(this)).setValue(value); was working :) –  Camille R Nov 30 '11 at 10:17
add comment



This works for me ( and now write this 100 times: "I will always read javadoc and look up public interfaces before asking trivial questions").

share|improve this answer
Now you must do this a 100 times: "I will always check my spelling before publishing my post on StackOverflow, especially before making remarks that will bite me in the a$$". –  Buhake Sindi Nov 29 '11 at 13:02
yup, I'll do it ! –  Camille R Nov 29 '11 at 13:03
grammar nazis can bite my shiny metal a$$ ;) –  Konstantin Pribluda Nov 29 '11 at 13:23
add comment

Use Field.getType().

Field f = Brush.class.getDeclaredField("myColor");
Class<?> c = f.getType();

You won't be able to use it to remove the cast from your code, though.

share|improve this answer
Huh, We've passed Java 1.4 era (hint: Generics). –  Buhake Sindi Nov 29 '11 at 13:03
add comment

Your Answer


