Dark Horse programmer ———— Loading, reflection, dynamic Proxy, enumeration of classes in Java

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

Class loading, reflection, dynamic proxy, enumeration


I. Loading of classesWhen a program wants to use a class, if the class has not yet been loaded into memory, the system initializes the class by loading, connecting, and initializing three steps.
1. Loading:It means reading the class file into memory and creating a class object for it.
★ The system creates a class object when any class is used
2. Connection:Verify that you have the correct internal structure and that it is consistent with other classes
Prepare to allocate memory for static members of the class and set default initialization values
Resolve to replace a symbolic reference in a class's binary data with a direct reference
3. Initialize:First static initialization, followed by member variable initialization


4. Initialization time for classesTo create an instance of a class
Access static variables for a class, or assign a value to a static variable
To invoke a static method of a class
Use reflection to force the creation of a Java.lang.Class object for a class or interface
Initializes a subclass of a class
To run a main class directly using the Java.exe command
5. Loader for class:Responsible for loading the. class file into memory and generating the corresponding class object for it.
Although we do not need to care about the class loading mechanism, we understand this mechanism and we can better understand the operation of the program.
The composition of the class loader:
Bootstrap ClassLoader root class loader (core class library)
Extension ClassLoader Extension class loader (tool plug-in class)
Sysetm ClassLoader System Class Loader (we custom Class)
The role of the class loader:
Bootstrap ClassLoader root ClassLoader: Also known as the Boot class loader, is responsible for loading Java core classes, such as system,string.
In the JDK Rt.jar file in the Lib directory of the JRE.
Extension ClassLoader Extension Class loader: Responsible for loading the jar packages in the extended directory of the JRE. In the JDK, in the Lib directory of the JRE, the ext directory.
System ClassLoader: is responsible for loading the class file from the Java command when the JVM starts, and the jar package and classpath specified by the CLASSPATH environment variable.



Two. Reflection1. Overview of ReflectionsJava reflection mechanism is in the running state, for any class, can know all the properties and methods of this class;
For any object, it can call any of its methods and properties;
This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.
To dissect a class, you must first obtain the bytecode file object for that class.
The anatomy uses the method in class. So first get the object of class type corresponding to each bytecode file.


2. Three ways to get the class object:
1). Using the object, call GetClass ();It is a method in the object class. This method is a normal method, not static, to be called through a reference to the object of the class.
Student stu = new Studetn ();
Class Stuclass = Stu.getclass ();


2). Static class attribute;Any "data type" has a "static property"--class property, which can get the class object
Int.class;
Class stuClass2 = Student.class;


3). Class forname () method;The class object can be obtained by using the static method Forname () in class.
public static Class forname (String className)
The classname here is a full-name qualified class name, which is the package name.
Class STUCLASS3 = Class.forName ("Cn.itcast.demo01_ three ways to get a Class object. Student");


Note: During a run, only one class object is generated. That is, either way, the class object gets the same object.


Three: Get and use the constructor method and the member variable in the class by reflection-the Member method
1. Get the constructor method: use all methods in classBulk acquisition:
Public constructor<?>[] GetConstructors (): Gets all the common constructor methods, and returns an array containing some Constructor object references that reflect this Class All public constructor methods for the class that the object represents
Example for (Constructor C:conarray) {
★ System.out.println (c);} The name of the constructed method, such as public cn.itcast.demo02_, gets the constructor of a class by class and calls the. Student (Boolean)
Public constructor<?>[] Getdeclaredconstructors (): Gets all the constructor methods. Includes public, protected, default, private construction methods.

Get a single:
Public constructor<t> getconstructor (class<?> ... parametertypes): Gets the constructor method of the publicly-owned parameter.
A class object that parametertypes the type of the constructed method formal parameter.
Example: Constructor con2 = Stuclass.getconstructor (Boolean.class);
Public constructor<t> getdeclaredconstructor (class<?> ... parametertypes): Gets the specified constructor method. can be private.



2. Call construction method: Using the method in constructorPublic T newinstance (Object ... initargs): Use this Constructor object to represent a new instance of the constructor method to create a declaration class for the constructed method.
Who calls this method creates an object using that constructor method. That is, the object of a class is returned, and the arguments passed are the actual arguments that are used to invoke the constructor method.
Example: obj = Con2.newinstance (true);
System.out.println ("obj =" + obj);//obj = Cn.itcast.demo02_ Gets the constructor of a class by class and invokes [email protected]


Because you want to access a private member, you will need to set up a "Cancel access restriction check" to make a violent visit.
public void Setaccessible (Boolean flag), constructor the method in the parent class AccessibleObject, cancels the access check.
Can be used to access private members in a class

3. Get member properties: Methods in classBulk acquisition:
Public field[] GetFields (): Get all member variables
Public field[] Getdeclaredfields (): Gets all the properties. including private ones.
Get a single:
Public Field GetField (String name): Gets the specified property
Example: Field f = Stuclass.getfield ("Stuname");
★ System.out.println (f);//The property name is printed, not the value. ★
Public Field Getdeclaredfield (String name): Gets the specified property. can be private.


4. Get and Set property values: Methods in the Field classpublic void Set (object Obj,object value): Note: Before setting, be sure to instantiate an object of this class first.
Parameter: obj-the object whose field should be modified, that is, the object of the class in which the field is located, and value-the new value of the field of the obj being modified.
public object get (object obj): Gets the value of the field, which is the object of the class in which the field is located, and extracts the value of the represented field.

Example:
Instantiate a Student object first
Object stuobj = Stuclass.getconstructor (). newinstance ();
Set a value for a field
F.set (Stuobj, "Jacky Cheung");
Gets the value of the field:
System.out.println ("Get the value of the field:" + f.get (stuobj));

For private properties, access is done through the package.
public void Setaccessible (Boolean flag),
Field class object. setaccessible (True);



5. Get member methods: Methods in class
Bulk acquisition:
Public method[] GetMethods (): Gets all the "common" methods. and the method inherited from the parent class also has ★
Public method[] Getdeclaredmethods (): Gets all methods, including private.
Example:
for (Method M:methodarray) {
System.out.println (m); Print method name (with parameter type) show (int) ★
Get a single:
Public method GetMethod (String name, Class<?> .... parametertypes): Gets the method that is publicly owned.
Formal parameter: Name: Method name; parametertypes: Type list of formal parameters, variable parameter
Public method Getdeclaredmethod (String name, Class<?> .... parametertypes): Gets a method. can be private.


6. Accessing member Methods: Methods in Method ClassNote: Before invoking a method, be sure to instantiate an object of this type first
public object invoke (Object Obj,object. args), object is the return value of the method after using the args argument, ★
Parameter: obj: The object to which the method belongs; args: the argument required to invoke the method

Equally violent visits
public void Setaccessible (Boolean flag)
Method object. Setaccessible (True)


Four. Important applications of Reflection:1. Run the contents of the configuration file by reflection
public class Demo {public static void main (string[] args) throws exception{/*//gets a class class object, using the three method, the static method class in class AClass =class.forname ("cn.itcast.Test reflection reads the configuration file. Line2");//Gets a class object again to get an object of that category, Object Obj=aclass.getconstructor () . newinstance ();//Gets a member of the class method M=aclass.getmethod ("Move", Int.class); M.invoke (obj, 20); *///defines a class class object class Aclass=class.forname (GetValue ("classname"));//by reflection, and calling the constructor method, create an object of that class objects obj=aclass.getconstructor ( String.class). Newinstance ("good Method");//Call its Member method Aclass.getmethod (GetValue ("methodname"), Int.class) by reflection. Invoke (obj, 50 );} By defining a method to get several things public static string GetValue (String str) throws ioexception{//defines a Properties collection map collection, To facilitate the reading and writing of files Properties Pro=new properties ();//define an input stream FileReader filein=new filereader (New file ("Pro.properties"));// Reads the contents of the file into the collection pro.load (Filein);//Closes the resource filein.close (); return Pro.getproperty (str);}} public class Line2 {private string name;public line2 (String name) {this.name =name;} public void Move (int n) {System.out.println ("name is:" +name+ "The age of the boy is" +n);}} 

2. Cross-generic check through genericsGenerics are only useful during compilation, you can load their class directly through generics, add something to a collection that declares generics

public class Demo {public static void main (string[] args) throws Exception  {//define a collection arraylist<integer> list= New Arraylist<> (); List.add (10);//Use reflection to create a class object of this type, calling its method class Aclass=arraylist.class;//list.getclass ();// Gets the object of its method, using the parameter object.class, the generic type method M=aclass.getmethod ("Add", Object.class); M.invoke (list, "Nihaoma"); SYSTEM.OUT.PRINTLN (list);}}
3. Set a property of an object to a specified value by using a generic type
public class Demo {public static void main (string[] args) throws Exception {cat c=new cat () SetValue (c, "name", "Bosimao"); s Etvalue (C, "age", 2); System.out.println ("Age:" +c.getage () + "Name:" +c.getname ());} private static void SetValue (Object obj, String fieldName, Object value) throws Exception {Class aclass=obj.getclass (); Field Field=aclass.getdeclaredfield (fieldName);//Because it is a private property that requires brute force access to field.setaccessible (true); Field.set (obj, value);}} public class Cat {private string name;private int age=0;public string getName () {return this.name;} public int getage () {return this.age;}}

Five. Dynamic Agent1. Overview of dynamic AgentsShould have done their own things, but invited others to do, the person invited is the proxy object.

This object is produced during the process of running the program, and the object that is generated during the program's operation is actually what we just reflected, so the dynamic agent is actually generating an agent through reflection.

2. Proxy mode:1). Student class has a coding () method, write the program;
2). If you need the coding () method in the test class, you need to instantiate a student directly and invoke the method;
If you want to add some additional functionality before or after the coding () method, you can add the student class without modifying the student class.
A "proxy class," The proxy class invokes methods in the student class.
3). After adding the proxy class, the test class does not need to face student directly, instead using the proxy class. New functionality has been added to the coding method in the proxy class.
Instead of using the underlying class directly, use a third-party proxy, and the agent can add some basic functionality
public class Demo {//test class public static void Main (string[] args) {/*student stu = new Student (); stu.coding (); *///Use proxy mode stude Ntproxy proxy = new Studentproxy ();p roxy.coding ();}} public class Studentproxy {//proxy class public void coding () {check (); new Student (). coding (); ZJ ();} Advance check for public void check () {System.out.println ("advance check ..."); Post-summary public void ZJ () {System.out.println ("post-summary ...");} public class Student {//Basic class public void coding () {System.out.println ("Do Project, write program ...");}

3. The steps of the dynamic agent;1). Customize a class, implement the Invocationhander interface, and override the Invoke () method in the interface
2). Use the Newproxyinstance () method in the proxy class to get the object of the surrogate class when you need to use the proxy class
3). The JDK can only do dynamic proxies for the interface, so define an interface for the class to be proxied and implement the interface
public class Demo {//test class public static void Main (string[] args) throws Exception {//Polymorphic subclass object, using the method in the proxy class newproxyinstace// Idao idaostu= (Idao) proxy.newproxyinstance (Class.forName ("cn.itcast.Test dynamic agent. Student"). getClassLoader (),// Student.class.getInterfaces (), New Myinvocationhander (New Student ())), Idao idaostu= (Idao) proxy.newproxyinstance ( Student.class.getClassLoader (), Student.class.getInterfaces (), New Myinvocationhander (New Student ())); Idaostu.write ()///Required method}}public class Myinvocationhander implements Invocationhandler {//Implement interface, proxy class private Object obj ;//Define the object that requires a proxy public Myinvocationhander (object obj) {this.obj=obj;} @Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {Object objmethod= Method.invoke (obj); show (); return objmethod;} private void Show () {System.out.println ("It's really bull!! ");}} Public interface Idao {//self-defined interface public void write ();} public class Student implements Idao {//custom class, requires proxy class @overridepublic void write () {System.out.println ("Hello, dynamic agent!! ");}}


Six. Enumeration1. Enumeration overviewA pattern "multi-case Mode": During the entire application run, some instances of the class are allowed only a few fixed, this pattern is "multi-sample Mode"
For example: Dice: Need 2 instances;
Poker: 54 instances;
The enumeration that is now said is based on the "multi-Instance pattern":
For example, when our program is running, we need three colors (red \ Green \ Blue), so we use a class MyColor to represent the color. Because we only need three colors, so the object of this class can only have three;

Public abstract class MyColor3 {//Abstract classes can also define multiple mode public static final MyColor3 red  = new MyColor3 ("Red") {@Overridevoid sho W () {System.out.println ("I am red!") ");}}; public static final MyColor3 green = new MyColor3 ("green") {@Overridevoid Show () {System.out.println ("I am green!") ");}}; public static final MyColor3 blue = new MyColor3 ("Blue") {@Overridevoid Show () {System.out.println ("I am blue!") ");}}; private string Colorname;private MyColor3 (string colorname) {this.colorname = ColorName;} Public String toString () {return this.colorname;} abstract void Show ();

2. Make enumeration steps: 1). Defining enumerations: Public enum XXXXX
2). Directly define an enumeration entry. Note: There can be other members, but the enumeration must be on the first line;
3). The enumeration can contain abstract methods;
4). Any enum class, inherited from: Enum class;
public enum MyColor3 {red ("red") {@Overridevoid Show () {System.out.println ("I am red!");}},green ("green") {@Overridevoid Show () {System.out.println ("I am green!"),}},blue ("Blue") {@Overridevoid Show () {System.out.println ("I am blue!");}; private string Colorname;private MyColor3 (string n) {this.colorname = n;} Public String Getcolorname () {return this.colorname;} abstract void Show ();

3. Enumeration of common methods in a class, using an enumeration object to invokeint CompareTo (E o)//Compare the index value of the enumerated item, do subtraction
String name ()//name of the enumeration entry fieldname
int ordinal ()//index value of the enumeration entry
String toString ()//The corresponding fieldname of the enumeration object
<T> T valueOf (class<t> type,string name)//Convert a string to an object of type
VALUES ()
Although this method is not found in the JDK document, each enumeration class has that method, and it is convenient to traverse all enumerated values of the enumeration class

public class Demo {public static void main (string[] args) {MyColor3 C1 = mycolor3.red; MyColor3 C2 = Mycolor3.blue; System.out.println (C2.compareto (C1));//subtraction of index values System.out.println ("name =" + C2.name ());//blue//int ordinal () System.out.println ("C2.ordinal ():" + c2.ordinal ()); System.out.println ("C1.ordinal ():" + c1.ordinal ()),//string toString () System.out.println ("C2.tostring ():" + C2.tostring ());//<t> T valueOf (class<t> type,string name) MyColor3 C3 = C1.valueof ("RED");// Converts a string to a MyColor3 object MyColor3 C4 = mycolor3.valueof (Mycolor3.class, "BLUE"); System.out.println (C3); System.out.println (C4);//values () mycolor3[] result = C1.values (); System.out.println ("Loop traversal:"); for (MyColor3 C:result) {System.out.println (c);}}}



Dark Horse programmer ———— Loading, reflection, dynamic Proxy, enumeration of classes in Java

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.