Help me, problem with java.lang.reflect.Field

N

Nicky

Hi,
I have a class like this
class A{
public String abc;
}

And i got another class use class A
{
A a = new A();
Field[] fields = a.getClass().getDeclaredFields();
}

The problem is that i can got the name of class A's fields but i cant
got the actual object to deal with. Because i dont know the name of the
class A's field, so i cant use a.a = "asd". I want to set value for
class A dynamically,

Please help me, thanks
 
G

Gordon Beaton

The problem is that i can got the name of class A's fields but i
cant got the actual object to deal with. Because i dont know the
name of the class A's field, so i cant use a.a = "asd". I want to
set value for class A dynamically,

Use one of the set methods provided by java.lang.reflect.Field, e.g.:

f.set(a, "asd");

/gordon
 
N

Nicky

Thanks gordon,
but how to get the value of field abc? i want to grap the object so
that i can take full control, so how?
 
G

Gordon Beaton

but how to get the value of field abc? i want to grap the object so
that i can take full control, so how?

You have already obtained the set of declared fields in an object "a".
To get the value of one of the fields in that object, call f.get(a) or
one of the other, typed methods (f.getLong() etc). To get the value of
the same field in another object (of the same class), do f.get(b),
etc. To set one of the fields, use f.set(a,val), f.set(b,val), etc.

This is described in the documentation for java.lang.reflect.Field,
which I would hope that you've read.

If this isn't what you are asking, you need to be much clearer.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top