reflect: is a Field an Array?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mikhail Teterin

    #1

    reflect: is a Field an Array?

    Hello!

    I'm going through the fields of a class one at a time and need to handle
    differently depending on whether they are arrays or scalars.

    What's the right way to make the distinction? The snippet below fails to
    detect arrays :(

    Thanks!

    -mi

    import java.lang.refle ct.*;
    .....
    for (Field field : getClass().getF ields()) {
    Type type = field.getGeneri cType();

    System.err.prin tln("Type of " + field + " is " + type + type.getClass() );
    if (type instanceof GenericArrayTyp e)
    System.err.prin tln(field + " is an array!");
    else
    System.err.prin tln(field + " is not an array");
    }
  • Robert Larsen

    #2
    Re: reflect: is a Field an Array?

    Mikhail Teterin wrote:
    Hello!
    >
    I'm going through the fields of a class one at a time and need to handle
    differently depending on whether they are arrays or scalars.
    >
    What's the right way to make the distinction? The snippet below fails to
    detect arrays :(
    >
    Thanks!
    >
    -mi
    >
    import java.lang.refle ct.*;
    ....
    for (Field field : getClass().getF ields()) {
    Type type = field.getGeneri cType();
    >
    System.err.prin tln("Type of " + field + " is " + type + type.getClass() );
    if (type instanceof GenericArrayTyp e)
    System.err.prin tln(field + " is an array!");
    else
    System.err.prin tln(field + " is not an array");
    }
    robert-desktop:~ $ cat Test.java
    import java.lang.refle ct.*;

    public class Test {
    private int nonArray;
    private int array[];

    public Test() {
    }

    public static void main(String args[]) throws Exception {
    Class c = Test.class;
    for (Field f : c.getDeclaredFi elds()) {
    System.out.prin tln("Field: " + f + " Is array: " +
    f.getType().isA rray());
    }
    }
    }
    robert-desktop:~ $ javac Test.java
    robert-desktop:~ $ java Test
    Field: private int Test.nonArray Is array: false
    Field: private int[] Test.array Is array: true
    robert-desktop:~ $

    Comment

    • Mikhail Teterin

      #3
      Re: reflect: is a Field an Array?

      Robert Larsen wrote:
      f.getType().isA rray()
      Many thanks!

      -mi

      Comment

      Working...