Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / December 2007

Tip: Looking for answers? Try searching our database.

reflect: is a Field an Array?

Thread view: 
Mikhail Teterin - 12 Dec 2007 01:03 GMT
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 Larsen - 12 Dec 2007 02:19 GMT
> Hello!
>
[quoted text clipped - 19 lines]
>    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:~ $
Mikhail Teterin - 12 Dec 2007 17:03 GMT
> f.getType().isArray()

Many thanks!

-mi


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.