Java reflection Summary

Source: Internet
Author: User

Java reflection Summary

I. Class class: note that it is not the same as the keyword class.

Class: Under the java. lang package; no public constructor; objects cannot be directly created; can only be obtained through a specific class; used to describe another type

An instance of the class indicates the classes and interfaces in the running Java application.

How to obtain a class object:
1) Class C1 = Class. forname ("(class name =) student ");
2) Class C2 = student. Class;
3) Student S1 = new student ("");
Class C3 = s1.getclass ();
No matter which method is used to obtain the same object, one type corresponds to one class object one by one. As shown in the following program, ousters is a common class under the test package.

Class C1 = Class. forname ("test. ouname ");
System. Out. println (C1 );
Class C2 = ou.pdf. Class;
System. Out. println (C2 = C1); // The result is: True.
Outera out = new outera ();
Class C3 = out. getclass ();
System. Out. println (C3 = C1); // The result is: True.

Class methods:

1. Int getmodifiers (); // get the int value of this modifier;

Modifiers. tostring (INT); // The modifier name returned. For example:

String modifier = modifier. tostring (c1.getmodifiers ());
System. Out. println (modifier );

2. class [] getinterfaces () // if this object represents a class, the returned value is an array that contains the Objects representing all interfaces implemented by this class. The order of interface objects in the array is the same as the order of interface names in the implements clause of the classes declared by the object. For example, the class exframe is as follows:

Public class exframe extends jframe implements actionlistener, serializable {
Public int intatt;
Private double result;
Public void actionreceivmed (actionevent arg0 ){
}
}

In the main method:

Class cc = exframe. Class;
Class [] interfaces = cc. getinterfaces ();
For (INT I = 0; I <interfaces. length; I ++ ){
System. Out. println (interfaces [I]);
}

The result is as follows:

Interface java. AWT. event. actionlistener
Interface java. Io. serializable

3. Field [] getdeclaredfields (); // obtain all attributes;
Field [] getfields (); // obtain all public attributes

Field [] fields = cc. getdeclaredfields ();

For (INT I = 0; I <fields. length; I ++ ){
System. Out. println (fields [I]);
}

The result is as follows:

Public int test. exframe. intatt
Private double test. exframe. Result

4. constructor <t> getdeclaredconstructor (class... parametertypes)
...: Variable length parameter, 0 ~ Multiple to determine which constructor to obtain;

5. Method getdeclaredmethod (string name, class... parametertypes)
Method [] getdeclaredmethods ()
Returns an array of method objects. These objects reflect the classes represented by this class object.
Or all methods declared by the interface, including public, protected, default (Package) access and private methods, but not inherited methods.

6. Class <?> [] Getparametertypes () to obtain the parameter table;
Class <?> [] Getexceptiontypes () returns the exception type;

Ii. reflection mechanism

The real purpose of reflection is to allow the JVM to dynamically load classes and call methods and modify attributes;

The class is loaded by parameters instead of being set by a program. The class name cannot appear in the source code;

It is generally in the source code: this class is loaded only when an object is created;

Reflection is not intended for application developers, but for framework developers;

T newinstance (); generate a new object;

Method getmethod (string name, class... parametertypes)

Iii. attributes: Field

The field class encapsulates all descriptions of attributes of a class, including modifiers, attribute types, attribute values, and attribute comments. It provides a series of get/set methods to obtain the Attribute Modification values.

There is a method in class: Field getfield (string name); you can get Field

Common Methods in field:

Object get (Object OBJ );
Void set (Object OBJ, object value );

Field F = C. getfield ("name"); // obtain the value of the name attribute of the OBJ object;
F. Get (OBJ); // equivalent to OBJ. Name;
F. Set (obj1, "hehe"); // set the f attribute of obj1 to hehe;

Iv. Method: Class Method

The method class encapsulates descriptions of all methods of a class, including modifiers, return types, method names, parameter lists, comments, and exception information. It also provides the invoke method to call itself.

Method has an invoke method: Object invoke (Object OBJ, object... ARGs)
Call the invoke method to upload at least one object,
The first parameter indicates the object on which the method is called;
The second parameter indicates the parameter passed to the method. It can be 0 or multiple;
Method M = C. getmethod ("move"); // call the move method of obj1;
M. Invoke (obj1, "hello", "hehe"); // equivalent to a traditional call: obj1.move ("hello", "hehe ");

Advantage: both methods and method parameters can be passed through parameters and are not written to the program;

5. constructor <t>

Constructor provides information about a single constructor of a class and its access permissions.

For non-argument constructor, you can directly call the newinstance () method of the class to construct an object.

For construction methods with parameters, use getconstructors () of the class and call newinstance (Object obj1,...) using the returned constructor object. For example:

Public class exframe extends jframe implements actionlistener, serializable {
Public int intatt = 9;
Private double result = 90.0;

Public exframe (jpanel pane, int I ){

}
Public void actionreceivmed (actionevent arg0 ){
System. Out. println ("actionreceivmed is invoked .....");
}
}

Constructor [] cons = cc. getconstructors ();
Exframe EF = (exframe) Cons [0]. newinstance (New jpanel (), new INTEGER (20 ));

6. Can the private attributes of objects be accessed through reflection?

The access permission is invalid for Java virtual machines. For private attributes, reflection can be accessed;
Field F = C. getdeclaredfield ("name ");
F. setaccessible (true); // This is valid only when the private attribute is added.
System. Out. println ("OBJ name is:" + F. Get (OBJ ));

Also valid for private member Methods: M. setaccessible (true );
The private constructor method is also valid. Con. setaccessible (true );
If the constructor is private, the new instance cannot be created outside, but reflection is acceptable;

But since it is set to private, do not break the encapsulation in special circumstances;

 

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/hakunamatata2008/archive/2009/03/17/3999749.aspx

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.