Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

about java: get `String[].class` from `String.class`, what if `String.class` is a "runtime type"? [duplicate]

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?

like image 579
watchzerg Avatar asked Nov 15 '12 05:11

watchzerg


People also ask

What is the difference between string and string [] in Java?

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.

Is string [] a class?

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.

Can we use string array in Java?

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.

Can a class extend a string?

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.


1 Answers

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); 
like image 158
Limeth Avatar answered Oct 11 '22 19:10

Limeth