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?
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.
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.
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.
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.
You need Field#getType()
.
Returns a
Class
object that identifies the declared type for the field represented by thisField
object.
getClass()
is a method inherited from Object
that returns the type of the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With