1

Using Java6 reflection API, Class.getDeclaredFields returns pretty weird values. Example of class field:

protected String[] arrF = new String[15];

Using getDeclaredFields on proper Class, a Field is returned:

  • name = arrF
  • type = [Ljava.lang.String;

The question: does [L prefix mean that the arrF is an array? Can I always rely on that, i.e. the field is an array iff type is prefixed with [L? If no, how can I get some information about "arrayness" of the field?

petrbel
  • 2,428
  • 5
  • 29
  • 49

3 Answers3

7

[ means one-dimension array ([[ is 2 dimensions array), and L followed by the class/interface name (Lclassname) is the type of that array.

Can I always rely on that, i.e. the field is an array iff type is prefixed with [L?

Yes. Or better, use Class#isArray().

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • Oh, I see. However, to get the dimension of the array, I need to parse the string to get count of the `[`, right? `Class` has no method doing that for me. – petrbel Apr 12 '15 at 08:47
  • @petrbel See this question: http://stackoverflow.com/questions/1764339/multi-dimension-length-array-reflection-java – Eng.Fouad Apr 12 '15 at 08:49
2

This is a much better way to do it!

    import java.lang.reflect.Field;
    import java.lang.reflect.Type;
    import static java.lang.System.out;

    public class ArrayFind {
        public static void main(String... args) {
             try {
                Class<?> cls = Class.forName(args[0]);
                Field[] flds = cls.getDeclaredFields();
                for (Field f : flds) {
                    Class<?> c = f.getType();
                    if (c.isArray()) {
                        // ....
                    }
                }

            } catch (ClassNotFoundException x) {
                x.printStackTrace();
            }
        }
    }

Btw. byte[] has name [B - [L is there for longs and/or references.

jakub.petr
  • 2,951
  • 2
  • 23
  • 34
0

What you got is so called binary name. Binary name is able to represent an array type as arrays in Java do not implement or extend an Array-like interface.

[Ljava.lang.String; means:

  1. [ single dimensional array
  2. L array of reference types and not primitives
  3. java.lang.String; represents the component type of the array
Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40