21

I have a method that requires something like Double.class as one of its inputs;

e.g.

someOutput = SomeObj.someMethod("parameter",Double.class);

I have another class that has a bunch of fields of different datatypes that I'd like to feed as input to this method in stead of explicitly writing Double.class of Integer.class etc etc.

I know this involves java reflection, but I'm not quite sure how to do what I want. I'm trying something like this but it isn't working:

for(Field field : Class.forName(MyClassWithLotsOfFields.class.getCanonicalName()).getFields()){ 
   someOutput = SomeObj.someMethod("parameter",field.getClass());
  //Do more stuff here...
}   

but field.getClass() is not giving me the actual class of the field from MyClassWithLotsOfFields but instead java.lang.reflect.Field

any ideas for how to do what I want?

2
  • 3
    What are you trying to achieve by doing Class.forName(MyClassWithLotsOfFields.class.getCanonicalName()) instead of just MyClassWithLotsOfFields.class? Commented Mar 28, 2014 at 0:08
  • 1
    I'm not the downvoter, but I suspect they may have been thinking that you could have gotten the answer by reading the javadoc for Field, which you already know about. Commented Mar 28, 2014 at 0:14

1 Answer 1

39

You need Field#getType().

Returns a Class object that identifies the declared type for the field represented by this Field object.

getClass() is a method inherited from Object that returns the type of the object itself.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.