Dark Horse programmer-Basic enhancement ------ Day 1 (2)

Source: Internet
Author: User

Reflection: Class class: maps various components in the Java class into corresponding Java classes.

Class describes JavaProgramClass class generated in, as we describe a person's age, gender, etc. Class is the class that describes class files.

A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, so their content in the memory is different. The space can be represented by objects respectively. These objects obviously have the same type. What is this type? This is the class.

How to obtain the Instance Object (class type) corresponding to each bytecode)

Class Name. class, for example, system. Class

Object. getclass (), for example, new date (). getclass ()

Class. forname ("Class Name"), for example, class. forname ("Java. util. date ");

What can be done through reflection: after obtaining the bytecode file, we can obtain the variables, methods, constructor, modifiers, packages, and other information in the class through the object.

Constructor class:Represents a constructor in a class.

Obtain the constructor [] constructors = Class forname ("Java Lang string ").Getconstructors ();

Obtain a constructor constructors = Class forname ("Java Lang string ").Getconstructor (Int. Class );Note that the difference between obtaining a method and obtaining a method is the parameter type.

With the constructor, you can create an object: new instance (); for example, string OBJ = (string) class. forname ("Java. lang. string "). newinstance (passing parameters );

Nine pre-defined class objects: eight basic types and one void class.

Field class:Class for getting member variables

The value of the member variable of the class to be reflected must be associated with an object, because the member variables of the class can have multiple, and each object has a corresponding variable value, to get the value of a variable, you must associate it with an object.

Public class reflectpoint {
PrivateInt X; for private member variables, violent reflection is required to obtain the X value of the object.Field fieldx = pt1.getclass ().Getdeclaredfield ("X");>Fieldx. setaccessible (true );
Public int y;

Public String str1 = "ball ";
Public String str2 = "basketball ";
Public String str3 = "itcast ";
Public reflectpoint (int x, int y ){
Super ();
This. x = X;
This. Y = y;
}
@ Override
Public String tostring (){
Return str1 + ":" + str2 + ":" + str3;
}

}

Public class reflecttest {

Public static void main (string [] ARGs) throws exception {

ReflectpointPt1= New reflectpoint (3, 5 );
Field fieldy = pt1.getclass (). getfield ("Y ");
// What is the value of fieldy? Is 5, Error! Fieldy is not a variable on an object, but a class. It is used to obtain the corresponding value on an object.
System. Out. println (Fieldy. Get (Pt1));
Field fieldx = pt1.getclass (). getdeclaredfield ("X ");
Fieldx. setaccessible (true );
System. Out. println (fieldx. Get (pt1 ));

Public String str1 = "ball ";
Public String str2 = "basketball ";
Public String str3 = "itcast ";

Changestringvalue (pt1 );

System. Out. println (pt1 );

}

Private Static voidChangestringvalue (Object OBJ)Throws exception {replace a character in a string with a new character
Field [] fields = obj. getclass (). getfields ();
For (field: fields ){
// If (field. GetType (). Equals (string. Class )){// Because all are the same bytecode, you can use the equal sign.
If (field. GetType () = string. Class ){
String oldvalue = (string) field. Get (OBJ );
String newvalue = oldvalue. Replace ('B', 'A ');
Field. Set (OBJ, newvalue );
}
}

}

}

Method class:Class for getting member Methods

You can call this method only by calling an object.

Public class reflecttest {

Public static void main (string [] ARGs) throws exception {

String str1 = "ball ";
Method methodcharat = string. Class. getmethod("Charat", Int. Class );Method Name and parameter list type
System. Out. println (Methodcharat. Invoke(Str1, 1 ));Call the invoke Method

System. Out. println (Methodcharat. Invoke(Null, 1); nullThis method is static.
System. Out. println (methodcharat. Invoke (Str1, New object [] {2}); The jdk1.4 parameter is an array

}//Differences between jdk1.4 and 1.5: 1.4 When an array needs to be passed as a parameter to the invoke method, each element in the array corresponds to a parameter in the called method. Therefore,CodeYou can also rewrite it

} // Charat. Invoke ("str", new object [] {1}) format.

Execute the main method in a Class Using Reflection:

Class testarguments {
Public static void main (string [] ARGs ){
For (string Arg: ARGs ){
System. Out. println (ARG );
}
}
}

Public class reflecttest {

Public static void main (string []ARGs) Throws exception {A parameter, which is an array of string []

// Testarguments. Main (New String [] {"111", "222", "333"}); a static method is called in a general program.
String startingclassname =ARGs [0];Assume that the first parameter is the class name of the unknown class to be executed.
Method mainmethod = Class. forname (startingclassname ). getmethod ("Main", string []. class); The jdk1.5 method is used here, And the received parameter is a string type array to obtain the mainmethod method.
// Mainmethod. Invoke (null,New object [] {New String [] {"111", "222", "333 "}}); // Jdk1.5 use new string [] {"1.4", "111", "222"} As a 333-compatible array (object [] OBJ)
Mainmethod. Invoke (null,(Object)New String [] {"111", "222", "333 "});// An object [], and split the object [] array into three string [] arrays. However, the main method passes a parameter, and an error is returned.

} //. You can use two solutions in the black box to avoid this situation.

}

Array reflection:

The same element type (INT here) and dimension (both one-dimensional and two-dimensional) are equal class bytecode.

Public class reflecttest {

Public static void main (string []ARGs) Throws exception {

int [] a1 = new int [] {1, 2, 3 };
int [] a2 = new int [4];
int [] [] a3 = new int [2] [3];
string [] A4 = new string [] {"A", "B ", "C" };< br> system. out. println (a1.getclass () = a2.getclass (); only true
system. out. println (a1.getclass () = a4.getclass ();
system. out. println (a1.getclass () = a3.getclass ();
system. out. println (a1.getclass (). getname ();
system. out. println (a1.getclass (). getsuperclass (). getname (); the parent class is Java. lang . object
system. out. println (a4.getclass (). getsuperclass (). getname (); the parent class is Java. lang. Object . The following subclass points to the reference of the parent class.

Object aobj1 = A1;
Object aobj2 = A4;
// object [] aobj3 = A1; an error is reported here, because the basic data type int is not included in the object array, the int is not included in the object. The basic type array cannot be converted to the object array.
object [] aobj4 = A3; the object contains a one-dimensional array of objects.
object [] aobj5 = A4;
system. out. println (A1);
system. out. println (A4);
system. out. println (arrays. aslist (A1);
system. out. println (arrays. aslist (A4);

System. Out. println (A1); // print the hash value directly.
System. Out. println (A4); // print the hash value directly.
System. out. println (arrays. aslist (A1); previously, the array was printed, and the aslist (Object OBJ) of the array tool class was used. Note that the_1 is an int array, so it prints the hash value of the int array object.
System. Out. println (arrays. aslist (A4); similarly, when string [] is passed in, it is an object [] object and it directly outputs the set element.

Printobject (A4); both the int array and the string array can be printed and reflected.

Printobject ("XYZ ");

}

Private Static void printobject (Object OBJ) {both the int array and the string array can be printed and reflected.
Class clazz = obj. getclass ();
If (clazz. isarray ()){
Int Len = array. getlength (OBJ );
For (INT I = 0; I <Len; I ++ ){
System. Out. println (array. Get (OBJ, I ));
}
} Else {
System. Out. println (OBJ );
}

}

}

Function of reflection:Implement FRAMEWORK Functions

Core issues to be addressed by frameworks and frameworks
I made a house for sale to users. Users Installed doors and windows and air conditioners themselves. My house was a framework. users needed to use my framework and insert the doors and windows into the framework I provided. The framework is different from the tool class. The tool class is called by the user class, while the framework is called by the user. The core issue to be solved by the Framework. When I write a framework (house), you may still be in elementary school and will not write programs yet? How can I call the framework program you wrote later?
Because you cannot know the name of the class to be called when writing a program, you cannot directly create an instance object of a class in the program. Instead, you must use the reflection method.
Comprehensive case:
First, use the new statement to create the instance objects of arraylist and hashset. This example uses eclipse to automatically generate the equals and hashcode methods of the reflectpoint class and compare the running results of the two sets.
Then, create the instance objects of arraylist and hashset by using the configuration file and reflection, and compare and observe the running results.
Elipse is introduced to explain how to manage resource files.

What is a framework? For example, we want to write a program scan. in the Java file, which of the following issues should be solved: Find @ in each of the read operations, find @, and then query a list. If the content after @ appears in the list, it indicates that this is an annotation that I can process and want to process. Otherwise, it indicates that it is not an annotation or at least not an annotation that I am interested in and can process. Then write the code for processing this annotation. Sun now provides an apt framework that completes all the preliminary work. We only need to provide a list of annotations that can be processed and the code that processes these annotations. Find the annotation we are interested in the apt box and notify or call our processing code for processing.

You do the door call lock, the lock is a tool, the door you do is called by the house, the house is a framework, the house and the lock are provided by others. The program does not handle exceptions, but the main method declaration throws exceptions, so that you can focus on the key code.
The class also provides a metaphor for the getresourceasstream method: If you ask me to buy a cola for your store every time, I 'd better buy a cola for you directly, that is, you can buy a cola directly.

Import java. Io. fileinputstream;
Import java. Io. inputstream;
Import java. util. arraylist;
Import java. util. collection;
Import java. util. hashset;
Import java. util. properties;

Public class reflecttest2 {

/**
* @ Param ARGs
*/

Public static void main (string [] ARGs) throws exception {
// Todo auto-generated method stub
/* Getrealpath (); // enter classname = java. util. arraylist/hashset in the new file config. properties source when Kingsoft bully/internal configuration file
Remember to use the complete path, but the complete path is not hard-coded but computed. */
Inputstream IPS = reflecttest2.class. getresourceasstream ("/CN/itcast/day1/resources/config. properties ");

Properties props = new properties ();
Props. Load (IPS );
IPS. Close ();
String classname = props. getproperty ("classname ");
Collection collections = (Collection)Class. forname(Classname). newinstance ();// This method is commonly used to obtain bytecode when constructing a framework.

// Collection collections = new hashset ();
Reflectpoint pt1 = new reflectpoint (3, 3 );
Reflectpoint pt2 = new reflectpoint (5, 5 );
Reflectpoint pt3 = new reflectpoint (3, 3 );

Collections. Add (pt1 );
Collections. Add (pt2 );
Collections. Add (pt3 );
Collections. Add (pt1 );

// Pt1.y = 7;
// Collections. Remove (pt1 );

System. Out. println (collections. Size ());
}

}

Introspection: it is the application of some methods in the API documentation used to operate JavaBean in the javaapi documentation. For example, you can obtain or set the attribute value. Javabean is a Java class with get and set attributes. Any Java class with such methods can be called JavaBean.

JavaBean can be used as a common class, but a common class is not necessarily a JavaBean, because this class does not necessarily have the get and set attributes. It is more convenient to use JavaBean because it encapsulates some methods and objects for convenience and class operations.

This is three ways to get the set attributes,JavaBean,Beaninfo,Propertyutils.

Import java. util. date;

Public class reflectpoint {
Private date Birthday = new date ();
Private int X;
Public int y;
Public reflectpoint (int x, int y ){
Super ();
This. x = X;
This. Y = y;
}
Public int getx (){
Return X;
}
Public void setx (int x ){
This. x = X;
}
Public int Gety (){
Return y;
}
Public void sety (INT y ){
This. Y = y;
}
Public date getbirthday (){
Return birthday;
}
Public void setbirthday (date birthday ){
This. Birthday = birthday;
}
}

Import java. Beans. beaninfo;
Import java. Beans. introspectionexception;
Import java. Beans. introspector;
Import java. Beans. propertydescriptor;
Import java. Lang. Reflect. invocationtargetexception;
Import java. Lang. Reflect. method;
Import java. util. Map;

Import org. Apache. commons. beanutils. beanutils; these two packages must be imported to the project.
Import org. Apache. commons. beanutils. propertyutils;

Public class introspectortest {

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs) throws exception {
Reflectpoint pt1 = new reflectpoint (3, 5 );
String propertyname = "X ";
// "X"> "getx">
Object retval =Getproperty (Pt1, propertyname);
System. Out. println (retval );
Object value = 7;
Setproperties (pt1, propertyname, value );

system. out. println ( beanutils. getproperty (pt1, "x "). getclass (). getname ();
beanutils. setproperty (pt1, "X", "9");
system. out. println (pt1.getx ();
/*
// New Features of Java 7
map = {name: "zxx", age: 18 };
beanutils. setproperty (MAP, "name", "lhm");
*/
beanutils. setproperty (pt1, "birthday. time "," 111 ");
system. out. println (beanutils. getproperty (pt1, "birthday. time ");
propertyutils. setproperty (pt1, "X", 9);
system. out. println ( propertyutils. getproperty (pt1, "x "). getclass (). getname ();
}

Private Static voidSetproperties(Object pt1, string propertyname, object Value) throws introspectionexception, illegalaccessexception, invocationtargetexception {
Propertydescriptor Pd2 = new propertydescriptor (propertyname, pt1.getclass (); extracted Set Method
Method methodsetx =Pd2.getwritemethod ();
Methodsetx.Invoke(Pt1, value );
}

Private Static object Getproperty (Object pt1, string propertyname) throws introspectionexception, illegalaccessexception, invocationtargetexception {
/* Propertydescriptor Pd = new propertydescriptor (propertyname, pt1.getclass ());
Method methodgetx = Pd. getreadmethod ();
Object retval = methodgetx. Invoke (pt1 );*/

BeaninfoBeaninfo = introspector. getbeaninfo (pt1.getclass ());This is the old method.BeaninfoAlthough it is troublesome, it is worth learning.
Propertydescriptor [] PPS = beaninfo. getpropertydescriptors ();
Object retval = NULL;
For (propertydescriptor PD: PDS ){
If (PD. getname (). Equals (propertyname ))
{
Method methodgetx = Pd. getreadmethod ();
Retval = methodgetx. Invoke (pt1 );
Break;
}
}
Return retval;
}

}

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.