f



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

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

0
1/25/2007 8:36:42 AM
comp.lang.java.programmer 52714 articles. 1 followers. Post Follow

3 Replies
577 Views

Similar Articles

[PageSpeed] 14

On 25 Jan 2007 00:36:42 -0800, Nicky wrote:
> 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

-- 
[ don't email me support questions or followups ]
g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e
0
n.o.t (582)
1/25/2007 8:44:36 AM
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?

On Jan 25, 3:44 pm, Gordon Beaton <n...@for.email> wrote:
> On 25 Jan 2007 00:36:42 -0800, Nicky wrote:
>
> > 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
>
> --
> [ don't email me support questions or followups ]
> g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e

0
1/25/2007 8:50:16 AM
On 25 Jan 2007 00:50:16 -0800, Nicky wrote:
> 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

-- 
[ don't email me support questions or followups ]
g o r d o n  +  n e w s  @  b a l d e r 1 3 . s e
0
n.o.t (582)
1/25/2007 9:21:04 AM
Reply: