How to get the Array Class for a given Class in Java?
Since Java 12, there is the arrayType()
method on java.lang.Class. With that:
Class<?> arrayOfFooClass = fooClass.arrayType();
The implementation of Class.arrayType()
just calls Arrays.newInstance(this, 0).getClass()
.
Java reflection getting array class of a given class
I think you want Array.newInstance(c, 0).getClass()
.
Getting class of array from class object
A simple method has been added to the API as late as JDK 12:
Class<?> arrayType = pojo.arrayType();
Before JDK 12, you needed a work-around like
Class<?> arrayType = Array.newInstance(pojo, 0).getClass();
using the old Array.newInstance(Class, int)
method. This actually creates a zero length array of the type specified by pojo
, then gets its Class
.
Obtaining the array Class of a component type
One thing that comes to mind is:
java.lang.reflect.Array.newInstance(componentType, 0).getClass();
But it creates an unnecessary instance.
Btw, this appears to work:
Class clazz = Class.forName("[L" + componentType.getName() + ";");
Here is test. It prints true
:
Integer[] ar = new Integer[1];
Class componentType = ar.getClass().getComponentType();
Class clazz = Class.forName("[L" + componentType.getName() + ";");
System.out.println(clazz == ar.getClass());
The documentation of Class#getName()
defines strictly the format of array class names:
If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting.
The Class.forName(..)
approach won't directly work for primitives though - for them you'd have to create a mapping between the name (int
) and the array shorthand - (I
)
Getting the class of the components of an array
Component Type
Use this:
array.getClass().getComponentType()
Returns the
Class
representing the
component type of an array. If this
class does not represent an array
class this method returnsnull
.
Reference:
Class.getComponentType()
Safe / Unsafe casting
Is there a way I can cast to Class
from Class returned by
getComponentType() without getting a
compiler warning?
take this method:
public <T> void doSomething(final T[] array) throws Exception{
final Class<? extends Object[]> arrayClass = array.getClass();
final Class<?> componentType = arrayClass.getComponentType();
final T newInstance = (T) componentType.newInstance();
}
Here's the generated byte code:
public void doSomething(java.lang.Object[] array) throws java.lang.Exception;
0 aload_1 [array]
1 invokevirtual java.lang.Object.getClass() : java.lang.Class [21]
4 astore_2 [arrayClass]
5 aload_2 [arrayClass]
6 invokevirtual java.lang.Class.getComponentType() : java.lang.Class [25]
9 astore_3 [componentType]
10 aload_3 [componentType]
11 invokevirtual java.lang.Class.newInstance() : java.lang.Object [30]
14 astore 4 [newInstance]
16 return
As you can see, the parameter type is erased to Object[], so the compiler has no way to know what T is. Yes, the compiler could use array.getClass().getComponentType()
, but that would sometimes fail miserably because you can do stuff like this:
Object[] arr = new String[] { "a", "b", "c" };
Integer[] integerArray = (Integer[]) arr;
doSomething(integerArray);
(In this case array.getClass().getComponentType()
returns String.class
, but T
stands for Integer
. Yes, this is legal and does not generate compiler warnings.)
how to get a array class using classloader in java?
Assuming your ClassLoader
implementation, MyClassLoader
is properly implemented, you'd simply pass the canonical name of the array class to the loadClass
method. For example, if you were trying to load the Class
for the class com.something.Foo
, you'd use
cl.loadClass("[Lcom.something.Foo");
You have to know that the class name for Array types is the character [
appended X number of times, where X is the number of array dimensions, then the character L
. You then append the qualified class name of the type of the array. And finally, you append the character ;
.
Therefore
Class<?> clazz = Class.forName("[Lcom.something.Examples;");
would get you the Class
instance returned by A[].class
if it was loaded by the same ClassLoader
.
Note that you won't be able to instantiate this type this way. You'll have to use Array.newInstance()
passing in the Class
object for A
, for a one dimensional array, the Class
object for A[]
for a two dimensional array and so on.
Create array in class and access the array in another class
Something like this?
Room.java:
class Room {
private Person[] persons;
public Room(Person[] persons){
this.persons = persons;
}
public void listAllPersons() {
// loop over array and print details
}
// add getters and setters as you need
}
Main class:
public static void main (String[] args) {
Person persons[] = new Person[3];
persons[0] = new Person("Me", 20);
persons[1] = new Staff("Papa", 60, 300);
persons[2] = new Person("Mama", 55);
Room room = new Room(persons);
room.listAllPersons();
}
Get type of array of class using Java reflection
I dont't know if it is optimal, but I do it in following way:
Array.newInstance(Class.forName("strClassName"), 0).getClass()
More over, strClassName must be the fully qualified name of the desired class.
How to get the class associated to an array type?
The class of new MySpecialClass[0]
is MySpecialClass[].class
so you can use:
example.mySpecialMethod(MySpecialClass[].class)
Related Topics
Main Method Not Found Even If I'Ve Declared It
Java:Read Last N Lines of a Huge File
Find Out What Jvm Eclipse Is Running On
Steganography in Lossy Compression (Java)
Random Number with Probabilities
Efficiently Finding the Intersection of a Variable Number of Sets of Strings
Java Bufferedimage Getting Red, Green and Blue Individually
How to Append a Node to an Existing Xml File in Java
Centering Text in a Jtextarea or Jtextpane - Horizontal Text Alignment
How to Iterate Over a Priorityqueue
How to Programmatically Inject a Java Cdi Managed Bean into a Local Variable in a (Static) Method
In Java Lambda's Why Is Getclass() Called on a Captured Variable
How to Take Screenshots Fast in Java
How to Fix Invalid Byte 1 of 1-Byte Utf-8 Sequence
Make Simpledateformat.Parse() Fail on Invalid Dates (E.G. Month Is Greater Than 12)