0

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?

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.