Java Reflection Technology

Source: Internet
Author: User

is to dynamically load a specified class and get 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 , Get Class object that is the bytecode file object that gets 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.

get this Class object, there are three ways:

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. based on the given class name to obtain for class loading

String classname = "Cn.itcast.reflect.Person";//From configuration file

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

//2. if we get the object, I don't know what type it is. The type used to get the object

Object obj = new person ();

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

//3. If you are explicitly getting a class's Class Object mainly used to transmit parameters

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:

two ways to create an object ( It 's actually the way the object was initialized when it was 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.itcast.bean.Person"); // class Loading

Direct access to the specified type

Clazz = person. class;

Get type based on object

Object obj = new person ("Zhangsan", 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.itcast.bean.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.itcast.bean.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.itcast.bean.Person");

// Gets the method that specifies the name.

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

// to run the specified method, the method object is, of course, the clearest, in order for the method to run, call the method object's Invoke method, but the method must be run explicitly to the object to which it belongs and to the actual parameters.

Object obj = clazz.newinstance ();

Method. Invoke (obj, "hehehe"); // Execute a method

}

// you want to run a private method.

public static void Method_3 () throws Exception {

Class clazz = Class.forName ("Cn.itcast.bean.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.itcast.bean.Person");

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

Method.invoke (Null,null);

}

Java Reflection Technology

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.