Here is a variable Class<?> cls
, now I want to get another Array Class Object
which component type is cls
.
For example, if cls
=String.class
, I want to get String[].class
; if cls
=int.class
, I want to get int[].class
, what should I do?
You see, It's quite easy to get String.class
from String[].class
:
Class<?> arrayCls = String[].class; if(arrayCls.isArray()){ Class<?> cls = arrayCls.getComponentType(); }
But I cannot find easy way to do the reverse.
Here is one possible solution:
Class<?> clazz = String.class; Class<?> arrayClass = Array.newInstance(clazz,0).getClass();
Is there any batter way to do this please?
String[] and String... are the same thing internally, i. e., an array of Strings. The difference is that when you use a varargs parameter ( String... ) you can call the method like: public void myMethod( String... foo ) { // do something // foo is an array (String[]) internally System.
Class String. The String class represents character strings. All string literals in Java programs, such as "abc" , are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created.
It is considered as immutable object i.e, the value cannot be changed. java String array works in the same manner. String Array is used to store a fixed number of Strings. Now, let's have a look at the implementation of Java string array.
Although the object extension is perhaps a bit type unsafe, you can extend a specific class called myclass just by using this myclass. Below we extended the string class with this string. This way only the string class can use the extended methods.
HRgiger's answer improved:
@SuppressWarnings("unchecked") static <T> Class<? extends T[]> getArrayClass(Class<T> clazz) { return (Class<? extends T[]>) Array.newInstance(clazz, 0).getClass(); }
Both of them instantiate an array object when invoked. To get the array type, use
Class<?> childType = ...; Class<?> arrayType = getArrayClass(childType);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With