Dark Horse programmer-java Learning reflection and common methods of class

Source: Internet
Author: User

--------Android Training, Java training, look forward to communicating with you! --------

Class

Instances of class classes represent classes and interfaces in a running Java application. An enumeration is a class, and a comment is an interface. Each array belongs to a class that is mapped to a class object, and all arrays that have the same element type and number of dimensions share the class object. The basic Java types (Boolean, Byte, char, short, int, long, float, and double) and the keyword Void are also represented as Class objects.
Class has no public constructor method. Class objects are constructed automatically by the Java virtual machine and by invoking the DefineClass method in the class loader when the class is loaded.


The class class instance method can be obtained by using the following three methods in general;

classtest{ Public Static voidMain (string[] args) throws Exception{class a=class.forname ("MyClass"); Class b=myclass.class; Class C=NewMyClass (). GetClass (); System. out. println (A==B);//Output TrueSystem. out. println (C==B);//Output True}}classmyclass{ Public voidprint (String value) {System. out. println (value);}}

As shown in the code above,
First, using the Class.forName () method, the method returns the class object associated with the classes or interfaces with the given string name.
The second is to use the class property of the corresponding classes directly,
The third, using the GetClass () method of the instantiated object of a class, is defined in the Java.lang.Object God class, which is the run-time class that returns this object
The class object obtained by these three methods is the same reference, that is to say, the class objects obtained by these three methods are the same.
There may be other ways, but these three methods are enough,

There are a number of common methods for class objects, which correspond to the use of class objects, as described in one side.

1. Methods of obtaining this class based on class object, including the methods of their own definition and inherited methods

GetMethods (), return type method[]
Returns an array containing some method objects that reflect the public member method for the class or interface represented by this class object, including those declared by the class or interface, and those inherited from the superclass and the hyper-interface.

Getdeclaredmethods (), return type method[]
Returns an array of method objects that reflect all methods of the class or interface declaration represented by this class object, including public, protected, default (package) access, and private methods, but not inherited methods.

GetMethod (String name, Class<?> .... parametertypes)
Returns a method object that reflects the specified public member methods for the class or interface represented by this class object.

Getdeclaredmethod (String name, Class<?> .... parametertypes)
Returns a method object that reflects the specified declared method of the class or interface represented by this class object.
......
Once you get the method object, you can use method's API methods,
For example, the Invoke () call method, GetName () obtains the name of this method, Getparametertypes () obtains the signature type of this method, Getreturntype () obtains the return type of this method ...

//method of Use 1Import java.lang.*; import Java.lang.reflect.*;classFanshen//Reflection{ Public voidprint (String value) {System. out. println (value);}}classtest{ Public Static voidMain (string[] args) throws Exception{class C=class.forname ("Fanshen");//gets a class object of class FanshenMethod M=c.getmethod ("Print", String.class);//obtain a method based on the name and method signature of the method (parameter type)M.invoke (C.newinstance (),"Printing conditions");//This method of invoking a new instance}}

2. According to the class object, get the field of this class, and you can change the value of the field


GetField (String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this class object.
GetFields ()
Returns an array containing some field objects that reflect all accessible public fields for the class or interface represented by this class object.
Getdeclaredfield (String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this class object.
Getdeclaredfields ()
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object.

//two methods of useImport java.lang.*; import Java.lang.reflect.*;classFanshen//Reflection{Private intF1;//the newly added three fieldsPrivate intF2;//the newly added three fields Public intF3;//the newly added three fields Public voidprint (String value) {System. out. println (value);}}classtest{ Public Static voidMain (string[] args) throws Exception{class C=class.forname ("Fanshen");//gets a class object of class FanshenMethod M=c.getmethod ("Print", String.class);//obtain a method based on the name and method signature of the method (parameter type)M.invoke (C.newinstance (),"Printing conditions");//This method of invoking a new instanceField[] F=c.getdeclaredfields (); for(intI=0; i<f.length;i++){//name of the field for the type of output fieldSystem. out. println (""+f[i].gettype () +" "+f[i].getname ());} Field f3=c.getfield ("f3");//gets the object of a F3 fieldFanshen fs=NewFanshen ();//instantiate an object and assign a value to the fieldfs.f3=8; F3.Set(FS,88888);//Use this field, and modify the FS objectSystem. out. println (FS.F3);//has been modified to 88888 }}

3. After obtaining the method, you can invoke the method's invoke () method to call the class's specified methods, the method class is in the package Java.lang.reflect.Method, when used to remember the import package.


This class is also a lot of methods, commonly used have getname (),
Getdeclaringclass ()
Returns a Class object that represents the classes or interfaces that declare the methods represented by this method object.
GetModifiers ()
Returns the Java language modifier for the method represented by this method object as an integer.
Getreturntype ()
Returns a Class object that describes the formal return type of the method represented by this method object.
Getparametertypes ()
Returns an array of Class objects in declaration order that describe the formal parameter types of the methods represented by this method object.
Invoke (Object obj, object ... args)
Invokes the underlying method represented by this method object for the specified object with the specified argument.
...... And other methods, the following code example writes a method of invoking a class using a reflection method, and obtains a printout of the return value.

//ThirdImport java.lang.*; import Java.lang.reflect.*;classFanshen//Reflection{ Public voidprint (String value) {System. out. println (value);}//add a new method to connect two strings Publicstring AddString (String arg1, String arg2) {string R=ARG1 +arg2;returnr;}}classtest{ Public Static voidMain (string[] args) throws Exception{class C=class.forname ("Fanshen");//gets a class object of class FanshenMethod M=c.getmethod ("Print", String.class);//obtain a method based on the name and method signature of the method (parameter type)Class[] Sign=Newclass[2];//method Signature Arraysign[0]=string.class; sign[1]=string.class; Method addstring=c.getmethod ("addstring", sign); System. out. println (Addstring.getname ());//call the method and receive the value returned by the methodString result= (String) Addstring.invoke (C.newinstance (),Newobject[]{"first parameter","a second parameter"}); System. out. println (Result);}}

The use of reflection, of course, far more than this, the idea of how far, can go far, class methods and many others, there are other ways to get thrown exceptions, methods to obtain the method modifier, etc., here is not all written out
The factory method pattern is useful to reflect the use of the sub-class, specifically in the other learning diary has. There is no repetition here.

While writing a review, write for most of the day, not easy ah.

Dark Horse programmer-java Learning reflection and common methods of class

Related Article

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.