Java Reflection Technology Detailed

Source: Internet
Author: User
Tags access properties

Reflection Technology: It's actually loading a specified class dynamically and getting all the content in that class. The bytecode files are encapsulated into objects and the contents of the bytecode files are encapsulated into objects, making it easier to manipulate those members. Simply put: the reflection technique can dissect a class.

The benefits of reflection: greatly enhance the extensibility of the program.

Basic Steps for Reflection:

1 , gets the class object, which is the byte-code file object that obtains the specified name.

2 , instantiate the object, and get the properties, methods, or constructors of the class.

3 , access properties, call methods, call constructors to create objects.

There are three ways to get this class object:

1: Obtained through the method getclass that each object has. Cons: You must create the class object before you can call the GetClass method.

2: Each data type (basic data type and reference data type) has a static property class. Cons: This class must be identified first.

The first two methods are not conducive to the extension of the program, because it is necessary to use a specific class to complete the program.

3: The method used in class, the static Forname method .

Specifies what class name to get what class bytecode file object, this way is strongest, as long as the class name of the string passed in.

//1. obtained for class loading based on the given class name

String classname = "Cn.xushouwei.cn.Person";//From configuration file

Class clazz = class.forname (classname);//This object represents Person.class

//2. If you get the object, don't know what type is used to get the object type

Object obj = new person ();

Class clazz1 = Obj.getclass ();//Get the object specific type

//3. If you are explicitly getting a class object that is used primarily to pass a reference

Class clazz2 = Person.class;

use of Reflection :

1), need to get the various components of the Java class, first need to obtain the class object, to obtain the classes object three ways:

class.forname (classname) for class loading

Obj.getclass () to get the type of the object

Class name. class is used to obtain the specified type,

2), the member method of the Reflection class:

Class clazz = Person.class;

method = Clazz.getmethod (MethodName, New CLASS[]{PARAMCLAZZ1, paramClazz2});

Method.invoke ();

3), the constructor of the Reflection class:

Constructor con = clazz.getconstructor (new class[]{paramclazz1, PARAMCLAZZ2,...})

Con.newinstance (params ...)

4), the properties of the Reflection class:

Field field = Clazz.getfield (FieldName);

Field.setaccessible (TRUE);

Field.setobject (value);

After you get the bytecode file object, you eventually need to create an object of the specified class:

There are two ways to create an object (which is actually how the object is initialized when it is instantiated):

1, call the constructor of the empty argument: the newinstance () method in the class is used.

2, call the constructor with parameters: first to get the constructor object for the specified argument list, and then initialize the object through the newinstance (actual argument) of the object of the constructor.

In summary, the second way, you must first clear the specific parameters of the constructor type, not easy to expand. so in general, a class that is reflected, the interior usually provides a constructor for a public null argument.

------------------------------------------------------

// How to generate an instance object that gets to a bytecode file object.

Class clazz = Class.forName ("Cn.xushouwei.cn.Person"); // class Loading

Direct access to the specified type

Clazz = person. class;

Get type based on object

Object obj = new person ("Xushouwei", 19);

Clazz = Obj.getclass ();

Object obj = Clazz.newinstance ();//The method invocation of the instantiated object is the null argument constructor in the specified class, which initializes the object to be created. When there is no empty argument constructor in the specified class, how do you create the class object? Please see Method_2 ();

public static void Method_2 () throws Exception {

Class clazz = Class.forName ("Cn.xushouwei.cn.Person");

Since there is no constructor for the null argument in the class, only the constructor that gets the specified argument is instantiated with the function.

// gets a constructor with parameters.

Constructor Constructor = Clazz. GetConstructor (String.class,int.class);

// to initialize an object, use the constructor's method newinstance ();

Object obj = constructor.newinstance ("Zhagnsan", 30);

// gets all constructors.

Constructor[] Constructors = clazz.getconstructors ();//contains only public

constructors = Clazz.getdeclaredconstructors ();//contains Private

for (Constructor con:constructors) {

System.out.println (con);

}

}

------------------------------------------------------

Reflect methods in the specified class:

// gets all the methods in the class.

public static void Method_1 () throws Exception {

Class clazz = Class.forName ("Cn.xushouwei.cn.Person");

Method[] methods = Clazz. GetMethods (); // gets the public method in the class and the public method in the parent class.

Methods = Clazz. Getdeclaredmethods (); // gets the methods in this class, including private methods.

for (Method method:methods) {

System.out.println (method);

}

}

// gets the specified method;

public static void Method_2 () throws Exception {

Class clazz = Class.forName ("Cn.xushouwei.cn.Person");

// Gets the method that specifies the name.

method = Clazz.getmethod ("show", Int.class,string.class);

// want to run the specified method, of course, the method object is the clearest, in order to let the method run, invoke method object Invoke method, but the method must be run to specify the object and the actual parameters.

Object obj = clazz.newinstance ();

Method. Invoke (obj, boy!, "Hello"); // Execute a method

}

// you want to run a private method.

public static void Method_3 () throws Exception {

Class clazz = Class.forName ("Cn.xushouwei.cn.Person");

// you want to get a private method. Must use Getdeclearmethod ();

Method method = Clazz.getdeclaredmethod ("method", null);

// private methods cannot be accessed directly because of insufficient permissions. Not to be accessed, can be done by means of violence.

method.setaccessible (true); Generally seldom used, because the private is hidden, so try not to access.

}

// reflection static method.

public static void Method_4 () throws Exception {

Class clazz = Class.forName ("Cn.xushouwei.cn.Person");

method = Clazz.getmethod ("function", null);

Method.invoke (Null,null);

}

Java Reflection Technology Detailed

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.