Use reflection in an array

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.