If we need a public method print (Object OBJ) to print the object information, what should we do if the input parameter obj is of the array type? Let's share it with you below:
Import java. Lang. Reflect. array;
Public class testarrayreflect {
Public static void main (string [] ARGs ){
String [] arr = new string [] {"AAA", "BBB", "CCC "};
String S = "123 ";
// Method for printing Object Information
Print1 (ARR );
Print1 (s );
System. Out. println ("----------------");
// Method 2 for printing Object Information
Print2 (ARR );
System. Out. println ();
Print2 (s );
}
/**
* Method 1 for printing Object Information
* @ Param OBJ
*/
Public static void print1 (Object OBJ ){
System. Out. println (obj. tostring ());
}
/**
* Method 2 of printing Object Information
* @ Param OBJ
*/
Public static void print2 (Object OBJ ){
Class CLS = obj. getclass ();
// If the object is an array
If (CLS. isarray ()){
// Obtain the length of the array
Int length = array. getlength (OBJ );
// Output each element in the array
For (INT I = 0; I <length; I ++ ){
System. Out. Print (array. Get (OBJ, I) + "");
}
} Else {
System. Out. println (obj. tostring ());
}
}
}
The running result is as follows:
[Ljava. Lang. String; @ de6ced
123
----------------
Aaa bbb ccc
123
From the results, we can see the information of the objects printed by the print1 method. What is the result? It is not what we want to display, but the information of the objects printed by the print2 method implemented by reflection is what we want.
It can be seen that although reflection is not used much in actual work, it can still play a magical role when dealing with some special problems.