Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection: get class of field

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?

like image 672
Tucker Avatar asked Mar 28 '14 00:03

Tucker


People also ask

How do you find the class object of associated class using reflection?

8. How to get the class object of associated class using Reflection? Explanation: forName(String className) returns the Class object associated with the class or interface with the given string name.

How do you get a class field?

The getField() method of java. lang. Class class is used to get the specified field of this class, which is the field that is public and its members. The method returns the specified field of this class in the form of Field objects.

What is reflection class in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

How do you create an instance of a class using reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.


1 Answers

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.

like image 64
Sotirios Delimanolis Avatar answered Sep 18 '22 03:09

Sotirios Delimanolis