Dark Horse programmer _ basic use of reflection

Source: Internet
Author: User

 

----------- Android training, Java training, and Java learning technology blog. We look forward to communicating with you! ------------

Reflection is to map various attributes in the Java class to another Java class. I thought I had a good idea about reflection. Later I did some experiments and found that I had a cup of cake. This experiment is to print out all the things of a class, yes, all, including how the methods are implemented, and then I will use the animals2 class enumerated in the previous article for reflection, the content in a cat and a dog cannot be reflected. I wanted to use recursion. As a result, you know, a class has five instance objects of its own, but when I use brute force reflection, each class has five instance objects of its own, and each of the five instance objects also contains five instance objects ....... As a result, the virtual machine does not quit and throws an exception. However, if only general information is printed, such as field, method, package, it is much simpler to print out the classname in order. The only problem is the typographical problem. First, let's get the code I wrote and explain it further:

Public class reflectanimal {public static void main (string [] ARGs) throws classnotfoundexception {class clazz = Class. forname ("it. cast. heima. animals2 "); printall (clazz);} // print the values of all fields, excluding the Private Static void printfileds (class clazz) of the parent class) throws classnotfoundexception {field [] fields = clazz. getdeclaredfields (); string modname; string fieldname; Class typename; For (field: fields) {field. set Accessible (true); modname = modifier. tostring (field. getmodifiers (); fieldname = field. getname (); typename = field. getType (); system. out. print ("" + modname); system. out. print ("" + typename. getname (); system. out. println ("" + field. getname () + "") ;}// print everything (package name, class name, field, method, but forget to get the constructor when writing) public static void printall (class clazz) throws classnotfoundexception {printpackage (clazz); printclassnm E (clazz); printfileds (clazz); printmethod (clazz);} // print out all methods Private Static void printmethod (class clazz) {method [] Methods = clazz. getdeclaredmethods (); string modname; string fieldname; Class retname; For (method: Methods) {method. setaccessible (true); modname = modifier. tostring (method. getmodifiers (); fieldname = method. getname (); retname = method. getreturntype (); Type [] types = method. g Etparametertypes (); system. out. print ("" + modname); system. out. print ("" + retname. getname (); system. out. print ("" + method. getname () + "("); stringbuffer sb = new stringbuffer (); For (type: types) {sb = sb. append (Type + ",");} If (sb. length ()! = 0) {system. out. println (sb. substring (0, sb. length ()-1) + ")"); continue;} system. out. println (Sb + ")") ;}// print out the class name Private Static void printclassname (class clazz) {system. out. print (modifier. tostring (clazz. getmodifiers (); system. out. println ("" + clazz. getname () + "{");} public static void printpackage (class clazz) {system. out. println (clazz. getpackage (). tostring ());}}

 

The output is as follows:

Package it. Cast. heima

Public it. Cast. heima. animals2 {

Private int age

Public java. Lang. string name

Protected [I

Public static final it. Cast. heima. animals2 dog

Public static final it. Cast. heima. animals2 cat

Public static final it. Cast. heima. animals2 monkey

Public static final it. Cast. heima. animals2 person

Public void scream ()

Private java. Lang. String say (class java. Lang. String, INT)

I added some fields for the enumeration class and added a method with a return value with parameters (increasing the difficulty ). In addition, I found that the above Code misses the constructor Method =, but it is similar. for reflection, you only need to know how to get the field of a class and basically want to reflect other content, just copy it. So I just want to explain how to obtain all the fields of a class. First, you need to load the class to be reflected into the virtual machine, otherwise it will be useless. There are three Loading Methods: class. forname (), classname. class, or call its getclass () method on an instance object. Okay, the byte code of the class is obtained, so you can find that there are multiple get methods in the class document. These are all returned package names of the following classes, modifiers, fields, methods, and so on. To obtain fields of this class, you can use getfields () to obtain all fields and return an array of fields. Then, let's look at the output through traversal, it is found that you get only public fields, and also include the parent class (in the above example, the parent class is object and there is no field ). Therefore, you can use the getdeclaredfields () method to obtain all fields, including public, private, protect, and default (nothing to write) modifiers, but not the parent class, this document also describes. It is not enough to obtain all the fields. You still have to have the access permission to call the setaccessible method. By default, it is not accessible to you. Just rape it and you will get it. This is what instructor Fang said in the video. I laughed while watching it.
= It's really funny. This is the so-called violent reflection... Now, we will not explain more about reflection on other content. The operations are similar.

Of course, it also needs to be called for reflection. It doesn't make sense if it is not reflected. If you want to call its method, or the Instance Object of the method, then invoke and pass an object, pass the parameters in. Static methods can write null to indicate that there is no object. If there is no parameter, null is entered. You can also create an object first. How to create a new object? Obtain the constructor and call the newinstance method. If the object has no constructor, you can directly clazz. newinstance. This method is developed by Sun to make it easier for experienced developers ^

The next day added: internal class reflection problems. In fact, the internal class reflection is similar, but the internal class name is a bit weird. The format is generally: External class name $ internal class name. class, so write the class name when loading in. In addition, for non-static internal class constructor, the compiler will carry a parameter by default. The parameter type is the reference of the Instance Object of the external class. In fact, it can be understood that, if there is no external class instance object, it will not be new to the internal class instance object, so the internal class constructor needs to pass an instance object reference. For static classes, the parameter type is null.

----------------------- Android training, Java training, Java learning technology blog, hope to communicate with you! ----------------------

For details, see:Http://edu.csdn.net/heima

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.