Asif Rafiq
Asif Rafiq

Reputation: 291

Java Reflection, Getting attribute Names and Types

I m facing problem while retriving fields types in class.

class Test {
    public int x;
    public int[] y;
    public String[] names;
}

public class Main {
    static void main(String[] args) {
        try {
            printAttributes(Class.forName("Test"));
        }
        catch(Exception ex){}
    }

    static void printAttributes(Class clazz) {
        Field[] fields=clazz.getFields();
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i].getType().getName().toString()+" "+ fields[i].getName().toString());
        }
    }
}

Output

int x  //its OK
[I y    //I need **int[] y**
[Ljava.lang.String; names  //I need  **java.lang.String[] names**

How can I get the attribute types in correct format?

Upvotes: 0

Views: 9079

Answers (2)

Kiril Kirilov
Kiril Kirilov

Reputation: 11257

The obscure phrase [Ljava.lang.String is the reified type of the array, where [L indicates that it is an array of reference type and java.lang.String is the component type of the array.

Excerpt from the book Java Generics and Collections by Maurice Naftalin, Philip Wadler, published by O'Reilly

Upvotes: 0

Bozho
Bozho

Reputation: 597076

You can't. Arrays' toString() method uses the [X convention. You can create you own utility that will do what you want. Like

public class ArrayUtils {
   public static String toClassName(Class<?> clazz) {
        if (clazz.isArray()) {
           return clazz.getComponentType().getName() + "[]";
        } else {
           return clazz.getName();
        }
   }
}

Update: Péter Török added this as answer but then deleted it. In fact you can use getCanonicalName() rather than getName(). That method does roughly what the about utility method does,i.e it will give you what you want. But you can still have your utility class if you want finer control on the representation (for example want to omit the FQN at some point, etc).

Upvotes: 2

Related Questions