# Setting a class field array via reflection

**URL:** <https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444>\
**Category:** Coding Questions\
**Created:** [December 9, 2018, 3:12pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444 "2018-12-09T15:12:06Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![Aleksi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/aleksi/32/11065_2.png) [@Aleksi](https://discourse.processing.org/u/Aleksi)\
**Post date:** [December 9, 2018, 3:12pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/1 "2018-12-09T15:12:06Z")

</div>

Hello once again.

The pipeline I’m developing uses a csv file to drive the animations. I’ve hit a stumbling block: I’d like to be able to parse a string into a class’s float array field using reflection. I feel like I’m close, but I’m not there yet. Here’s the stripped down logic:

```auto
import java.lang.reflect.*;
import java.util.Arrays;

String tester = "radii:{1.0, 2.0, 3.0}"; 

Tmp tmp = new Tmp();

void setup(){  

    String[] field_vals = splitTokens(tester, ":");
    
    String attr = field_vals[0];
    String[] vals = splitTokens(field_vals[1], "{}, ");
    println("attr:",attr);
    printArray(vals);
    
    float[] fa = new float[vals.length];
    for (int cnt=0; cnt<vals.length; cnt++){
      fa[cnt] = Float.parseFloat(vals[cnt]);
    }
    printArray(fa);
    
    try {
        Field field = tmp.getClass().getDeclaredField(attr);
        field.set(attr, fa); 
        // or this? ...see link below...
        //field.set(t, values.toArray(Array.newInstance(field.getType().getComponentType(), values.size()));
    } catch (NoSuchFieldException e) { println(tmp.getClass()," has no field ",field_vals[0]);
    } catch (Exception e) { throw new IllegalStateException(e); }

    tmp.printFields();
}

class Tmp {
  float[] radii;
  
  Tmp(){} 
  
  void printFields(){
    println("TMP: radii: ",radii);
  }
}

```

I came across something [that looked like a solution](https://stackoverflow.com/questions/20083925/setting-value-of-array-using-java-reflection), but I can’t get it to work.

Any help appreciated! Thank you.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [December 9, 2018, 3:47pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/2 "2018-12-09T15:47:54Z")

</div>

```java
  final float[] arr;

  try {
    final Field f = tmp.getClass().getDeclaredField(attr);
    f.setAccessible(true);
    arr = (float[]) f.get(tmp);
  } 
  catch (final ReflectiveOperationException e) { 
    throw new RuntimeException(e);
  }

  println(arr);
  exit();
}

```

---

<div class="post-metadata">

**Author:** ![Aleksi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/aleksi/32/11065_2.png) [@Aleksi](https://discourse.processing.org/u/Aleksi)\
**Post date:** [December 9, 2018, 3:56pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/3 "2018-12-09T15:56:52Z")

</div>

Thank you for the quick response, GTL!

However, I’m not understanding how this _sets_ `tmp.radii` to the float array… This just sets `arr` to null within the local scope of the try block…

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [December 9, 2018, 4:11pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/4 "2018-12-09T16:11:13Z")

</div>

> [@Aleksi](#):
>
> This just sets `arr` to null within the local scope of the try block…

B/c the moment it reads the field Tmp::_radii_ it is still `null`! 🙄  
How about instantiating the array right way inside class Tmp? 💡

```java
class Tmp {
  static final int RADII = 3;
  final float[] radii = new float[RADII];
}

```

---

<div class="post-metadata">

**Author:** ![Aleksi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/aleksi/32/11065_2.png) [@Aleksi](https://discourse.processing.org/u/Aleksi)\
**Post date:** [December 9, 2018, 4:20pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/5 "2018-12-09T16:20:30Z")

</div>

> B/c the moment it reads the field Tmp:: _radii_ it is still `null` ! 🙄

Of course… 🤨 That’s why I don’t understand your solution.

But that’s exactly half of the problem I’m facing: I don’t know how large my array is until I obtain the string from the csv. The other half is setting the array to the values contained in the string.

The goal is to set the `radii` float array from an external string without knowing its size. The string also contains the name of the class to be instantiated. That’s why I need to use reflection.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [December 9, 2018, 4:38pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/6 "2018-12-09T16:38:06Z")

</div>

> [@Aleksi](#):
>
> The goal is to set the _radii_ `float` array from an external string without knowing its size.

```java
  final float[] arr = float(vals);;

  try {
    final Field f = tmp.getClass().getDeclaredField(attr);
    f.setAccessible(true);
    f.set(tmp, arr);
    println(f.get(tmp));
  } 
  catch (final ReflectiveOperationException e) { 
    throw new RuntimeException(e);
  }

  exit();
}

```

---

<div class="post-metadata">

**Author:** ![Aleksi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/aleksi/32/11065_2.png) [@Aleksi](https://discourse.processing.org/u/Aleksi)\
**Post date:** [December 9, 2018, 4:55pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/7 "2018-12-09T16:55:08Z")

</div>

That pretty much replicates my original code, except that I didn’t know I could just assign `vals` to `arr` by simply recasting them (instead of going through my original loop). 😀

The reason for posting my question is that this doesn’t work for me. When I run this I get the exception `java.lang.IllegalArgumentException: Can not set [F field sketch_18209b$Tmp.radii to java.lang.String`.

I don’t understand why I get this exception, and I don’t know how to solve it. 😖

---

<div class="post-metadata">

**Author:** ![Aleksi](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/aleksi/32/11065_2.png) [@Aleksi](https://discourse.processing.org/u/Aleksi)\
**Post date:** [December 9, 2018, 5:20pm UTC](https://discourse.processing.org/t/setting-a-class-field-array-via-reflection/6444/8 "2018-12-09T17:20:11Z")

</div>

Actually… it does work!

I read the exception more carefully… how could it think I was trying to assign a string to the float array?

D’OH! Because I was using the wrong parm in `field.set()`!

I was passing in the attr as the first parm, not the class. 🤪 I’ll blame my oversight on tiredness and age.

```auto
// wrongBad: field.set(attr, arr);
field.set(tmp, arr); // rightGood

```

Sorry for distracting you from your other matters. Thank you again, GTL, for your customary willingness to help someone in need!
