VishalDevgire
VishalDevgire

Reputation: 4268

How to get original class of a field declared in java class

Here we go, suppose if i have class Name :

class Name {
  String firstName, lastName;
  // getters and setters, etc.
}

and then Name class's object is declared somewhere in other class :

class Other {
  Name name;
  // getter and setters, etc.
}

Now if i do something like :

Other o = new Other();
Field[] fields = o.getClass().getDeclaredFields();

fields[0] --> is 'name' the Object of 'Name' class

but when i say field[0].getClass() :

It gives me java.lang.reflect.Field class object and not Name class object.

How can i get original class object from a field like 'name'

Upvotes: 2

Views: 3272

Answers (5)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136012

Field.getType method returns a Class object that identifies the declared type for the field represented by this Field object.

Upvotes: 3

Sanyam Goel
Sanyam Goel

Reputation: 2180

This should help


Other o = new Other();
Class<?> classTemp1 = o.getClass();
Field[] allFields = classTemp1.getDeclaredFields();

Now u can query each field for name ,type etc

Upvotes: 2

Juvanis
Juvanis

Reputation: 25950

Based on Evgeniy's answer, this line is what you are looking for:

String actualClassName = fields[0].getType().getName();

Upvotes: 1

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

fields[i].getType()

Please check http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#getType()

getType() Returns a Type object that represents the declared type for the field represented by this Field object.

field[0].getClass()

Will return you the Type object that represents field[0] which is obiviously field[0].

Upvotes: 1

MadProgrammer
MadProgrammer

Reputation: 347204

Basically, you need to ask the field for the value of a specific instance, something like

Name name = (Name)fields[0].get(o);

Now. It's pretty dangrous to do a blind cast like this, I'd be probably simply assign it to a Object first and then do instanceof or maybe use Field#getName to determine the name of the field and take action from there...

nb- I'd make mention of getType, but Evgeniy Dorofeev beat me to it and I don't want take away from his answer

Upvotes: 1

Related Questions