1

I want the underlying class from a static array. For example if it says String[].class I want to get String.class

    String[] foo = new String[0];
    System.out.println(foo.getClass());

Output

class [Ljava.lang.String;
0

1 Answer 1

6

Use Class#getComponentType():

Class<?> type = foo.getClass().getComponentType();
System.out.println(type); // class java.lang.String

From the docs:

Returns the Class representing the component type of an array. If this class does not represent an array class this method returns null.

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

1 Comment

And if you're not sure foo is an array, you might want to first check foo.getClass().isArray(), instead of testing whether getComponentType() returns null.

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.