Reputation: 4151
My program has a class that has a large number of fields. I need to be able to create a new instance of this class from two previously existing instances. It would randomly choose which fields it gets from which of the two previous instances.
Obviously I could just do a bunch of these:
if(random.nextBoolean())
this.value = a.value;
else:
this.value = b.value;
However, I have always been intrigued by some of the methods found in ClassName.class. I have tried researching this before but, I never had any luck. So let me show you what I would like to do:
for(int i = 0; i < Specimen.class.getDeclaredFields().length; i++){
if(random.nextBoolean())
this.fields[i] = a.fields[i];
else
this.fields[i] = b.fields[i];
It is my understanding that this is not possible with reflection, is there another way?
Upvotes: 0
Views: 69
Reputation: 347314
Field
holds more then just the value of the field.
To get the value of the field, you need to use one of the set
/get
methods. For example.
if(random.nextBoolean())
this.fields[i].set(a.fields[i].get());
else
this.fields[i].set(b.fields[i].get());
Upvotes: 1