Connecting Tech Pros Worldwide Help | Site Map

reflect: is a Field an Array?

  #1  
Old December 12th, 2007, 01:05 AM
Mikhail Teterin
Guest
 
Posts: n/a
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.reflect.*;
.....
for (Field field : getClass().getFields()) {
Type type = field.getGenericType();

System.err.println("Type of " + field + " is " + type + type.getClass());
if (type instanceof GenericArrayType)
System.err.println(field + " is an array!");
else
System.err.println(field + " is not an array");
}
  #2  
Old December 12th, 2007, 02:25 AM
Robert Larsen
Guest
 
Posts: n/a

re: reflect: is a Field an Array?


Mikhail Teterin wrote:
Quote:
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.reflect.*;
....
for (Field field : getClass().getFields()) {
Type type = field.getGenericType();
>
System.err.println("Type of " + field + " is " + type + type.getClass());
if (type instanceof GenericArrayType)
System.err.println(field + " is an array!");
else
System.err.println(field + " is not an array");
}
robert-desktop:~ $ cat Test.java
import java.lang.reflect.*;

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.getDeclaredFields()) {
System.out.println("Field: " + f + " Is array: " +
f.getType().isArray());
}
}
}
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:~ $
  #3  
Old December 12th, 2007, 05:05 PM
Mikhail Teterin
Guest
 
Posts: n/a

re: reflect: is a Field an Array?


Robert Larsen wrote:
Quote:
f.getType().isArray()
Many thanks!

-mi
Closed Thread


Similar Threads
Thread Thread Starter Forum Replies Last Post
Reflection over an array of objects Flomo Togba Kwele answers 1 January 31st, 2008 02:45 AM
passing a struct with an array by reference abhiM answers 11 May 4th, 2007 08:15 AM
How to use reflection to read an array in an unmanaged structure bill answers 3 December 7th, 2006 11:05 PM
Dynamic array creation None answers 1 June 2nd, 2006 03:35 PM