Sort out java knowledge points with gangge-reflection and proxy (17th) and java knowledge points

Source: Internet
Author: User

Sort out java knowledge points with gangge-reflection and proxy (17th) and java knowledge points

What is the reflection mechanism?
The reflection mechanism is in the running state. For any class, all the attributes and methods of this class can be known.
Any object can call one of its methods and attributes.
The function of dynamically calling an object method is called the reflection mechanism of the java language.

What can reflection mechanism do?
The reflection mechanism mainly provides the following functions:
√ Determine the class to which any object belongs during running
√ Construct objects of any class at runtime
√ Determine the attributes and methods of any class at runtime
√ Call the method of an object at runtime
√ Generate dynamic proxy

Get the complete package name and class name through an object
Package com. hzg; public class TestReflect {public static void main (String [] args) throws Exception {TestReflect testReflect = new TestReflect (); System. out. println (testReflect. getClass (). getName (); // result com. hzg. testReflect }}
Obtain complete attributes and methods through an object
Class clazz = Person. class (); // 1. Create the Person object Person p = (Person) clazz. getInstance (); // 2. Call the specified attribute Filed f1 = clazz during runtime through reflection. getField ("name"); f1.set (p, "LiudeHua"); // 3. Call the specified Method m1 = clazz during runtime through reflection. getMethod ("show", String. class); m1.invoke (p, "CHN ");

Note: The Class is not a key word class, the Class is a class name, and the Class is a key word identifier is a class

Get the class instance (3 methods)
① Call the. class Attribute of the runtime class itself
Class clazz = Person. class;
② Get through the runtime Class Object
Person p = new Person ();
Class clazz = p. getClass ();
③ Obtained through static class methods
Class clazz = Class. forName ("com. hzg. TestReflect ");

Package com. hzg; public class TestReflect {public static void main (String [] args) throws Exception {Class <?> Class1 = null; Class <?> Class2 = null; Class <?> Class3 = null; // ① static method (usually in this form) class1 = Class. forName ("com. hzg. testReflect "); // ② get class2 for the runtime Class Object = new TestReflect (). getClass (); // The class itself. class Attribute class3 = TestReflect. class; System. out. println ("Class Name" + class1.getName (); System. out. println ("Class Name" + class2.getName (); System. out. println ("Class Name" + class3.getName ());}}
Obtain the parent class and implementation interface of an object
1 package com. hzg; 2 import java. io. serializable; 3 public class TestReflect implements Serializable {4 private static final long serialVersionUID =-2862585049955236662L; 5 public static void main (String [] args) throws Exception {6 Class <?> Clazz = Class. forName ("com. hzg. TestReflect"); 7 // get the parent Class 8 Class <?> ParentClass = clazz. getSuperclass (); 9 System. out. println ("the parent class of clazz is:" + parentClass. getName (); 10 // The parent class of clazz is: java. lang. object11 // obtain all the 12 Class interfaces <?> Intes [] = clazz. getInterfaces (); 13 System. out. println ("clzz interfaces:"); 14 for (int I = 0; I <intes. length; I ++) {15 System. out. println (I + 1) + ":" + intes [I]. getName (); 16} 17} 18}

 

What can I do with a class instance?
① You can create objects of the corresponding runtime class
② Obtain the complete class structure of the corresponding running class: attributes, methods, constructors, packages, generics, annotations, exceptions, and internal classes.
For example, Method [] m1 = clazz. getMethods (): obtains all public methods of the class and its parent class.
Method [] m1 = clazz. getDeclaredMethods (): All Modifiers
But does not include the parent class. Only all modifier methods in this class are available.
③ Call and run is the structure (attributes, methods, constructors) specified in the class)
√ Obtain the specified attribute: Field name = clazz. getField ("name ");
√ Set the specified public attribute: name. set (p, "hzg ");
√ Set the specified private property:
Field name = clazz. geDeclaredtField ("name ");
Name. setAccessible (true );
Name. set (p, "hzg ");
√ Obtain the specified Method: Method m1 = clazz. getMethod ("show ");
√ Call the specified method:
Object obj = m1.invoke (p); The return type is the return type of the method.

√ Call static method: m1.invoke (Person. class );
√ Call the specified method with parameters:
Method m1 = clazz. getDeclatedMethod ("show1", String. class );
Object obj = m1.invoke (p, "hzg ");

√ Call Constructor con = clazz. getDeclaredConstructor ();
√ Call the parameter constructor, which is consistent with the parameter method

Java reflection application --- proxy

1. Static proxy (static proxy based on interface polymorphism)

1 interface ClothFactory {2 void productCloth (); 3} 4 // delegate class 5 class NikeClothFactory implements ClothFactory {6 @ Override 7 public void productCloth () {8 sysytem. out. printLn ("NIKE factory produces a batch of clothes"); 9} 10} 11 // Agent class 12 class ProxyFactory implements ClothFactory {13 ClothFactory cf; 14 public ProxyFactory (ClothFactory cf) {15 this. cf = cf; 16} 17 @ Override18 public void productCloth () {19 sysytem. out. printLn ("the agent class starts to be executed, and the agent fee is 1000"); 20 cf. productCloth (); 21} 22} 23 24 public class Test {25 public static void main (String [] args) {26 // ① create a proxy object 27 NikeClothFactory nike = new NikeClothFactory (); 28 // ② create a proxy object 29 ProxyFactory proxy = new ProxyFactory (nike ); 30 // ③ call the proxy class Object method 31 proxy. productCloth (); 32} 33}

Static proxy summary:
① Both the proxy class and the proxy class implement the same interface.
② Both the proxy class and the proxy class implement the methods in the interface


2. Dynamic proxy (reflection-based Dynamic proxy)

1 interface ClothFactory {2 void productCloth (); 3} 4 // delegate class 5 class NikeClothFactory inplements ClothFactory {6 @ Override 7 public void productCloth () {8 sysytem. out. printLn ("NIKE factory produces a batch of clothes "); 9} 10} 11 // ① The InvocationHandler interface 12 class MyInvocationHandler implements InvocationHandler {13 // ② declares the interface's proxy class 14 Object obj; 15 // ③ create a method to instantiate the proxy class 16 public Object bind (Object obj) {17 this. obj = obj; 18 return Proxy. newProxyInstance (19 obj. getClass (). geyClassLoder (), 20 obj. getClass (). getInterfaces (), this); 21} 22 // ④ method for implementing the InvacationHandler interface 23 // implementation of this method: when calling the object method of the proxy class, will be converted to it and calls 24 @ Override25 public Object invoke (Object proxy, Method method, Object [] args) {26 Object returnVal = method. invoke (obj, args); 27 return returnVal (); 28} 29} 30 // call to implement 31 public class Test {32 public static void main (String [] args) {33 // ① old rule: Create a proxy object 34 NikeClothFactory nike = new NikeClothFactory (); 35 // ② old rule: Create a proxy object 36 MyInvocationHandler hander = new MyinvocationHanlder (); 37 ClothFactory proxyCloth = (ClothFactory) hander. bind (nike); 38 // ③ old rule: Call the method 39 proxyCloth of the proxy object. productCloth (); 40} 41}

 

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.