Java reflection and dynamic proxy detailed and instance code _java

Source: Internet
Author: User
Tags aop arrays mul object object reflection throwable

One, reflection in Java

1. Load class properties and method instance code by reflection:

/** * Java.lang.Class is the source of reflection * We created a class that generates the corresponding class file by compiling (Javac.exe), after which we load the class file via Java.exe (the JVM loader) * This class file is loaded into memory, is a run-time class, there is a buffer, this run-time class is an example of the classes * Each runtime class is loaded only once, */class<studentexam> clazz = Stud
    Entexam.class;
    Studentexam Studentexam = Clazz.newinstance ();
     
    System.err.println (Studentexam);
    System.out.println (Clazz); Field field = Clazz.getfield ("id"); The specified property of the Run-time class is called by a property: The property is public type field field = Clazz.getdeclaredfield ("id"); property is a non-public type field[] fields = Clazz.getdeclaredfields ();
    Gets all declared properties of the runtime class itself (not the parent class), and the parent class uses Clazz.getfields ();
      for (Field field2:fields) {int i = field2.getmodifiers ();
    String type = modifier.tostring (i);//Get the data type SYSTEM.OUT.PRINTLN (type) of the field property;
    } field.setaccessible (True);
    Field.set (Studentexam, 11);
     
    System.err.println (Studentexam.getid ());
    To invoke the specified method of the Run-time class by reflection methods = Clazz.getmethod ("SetId", Integer.class); Method.invoke (Studentexam, 123); Invokes the specified method of the Run-time class method[] methods = Clazz.getmethods (); Gets all the method method[] Methods2 = Clazz.getdeclaredmethods () that is declared public in all Run-time classes and their parent classes, or gets the methods for declaration in the runtime class itself class (method Metho
    D2:methods) {System.out.println (Method2.getname ());
    //* Gets the Run-time class of the object through the object's GetClass () method, Exam Exam = new Exam ();
 Class Clazzexam = Exam.getclass ();

2. Class Loader ClassLoader

/**
   * Description: Class loader, loading Xx.properties file, and reading data
   * @param
   * @author xiazhongwei
   * @data September 29, 2016: Afternoon 5 : 32:56
   * @return/public
  void ClassLoader () throws IOException {
    //method One, load from current project
    ClassLoader Loader = This.getclass (). getClassLoader ();
    Path is under package write: Com\\able\\onlineexam\\resources\\config.properties
    inputstream instream = Loader.getresourceasstream ("Config.properties");
    Method Two, loading the file from the specified path
    //FileInputStream FileInputStream = new FileInputStream ("Config.properties");
     
    Properties Properties = new properties ();
    Properties.load (instream);
    Properties.load (FileInputStream);
    String prop = Properties.getproperty ("domain");
    SYSTEM.OUT.PRINTLN (prop);
  }

3. Dynamic Proxy

Static proxies: The types of proxy classes and target objects are determined during compilation and are not conducive to program expansion. At the same time, each proxy class can only serve one interface, so the program development will inevitably generate too many agents.

Dynamic Proxy: A method by which a client invokes other objects through a proxy class, and a proxy object that dynamically creates the target class as needed when the program is run.

Principle of Agent design pattern:

Use a proxy to wrap the object, and then replace the original object with the proxy object, and any calls to the original object are passed by proxy, and the proxy object determines whether and when the method is called

Package com.test.junit;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
 
Import Java.lang.reflect.Proxy;
    public class Proxytest {public static void main (string[] args) {Realsubject realsubject = new Realsubject ();
    Myinvocationhandler Myinvocationhandler = new Myinvocationhandler ();
    Object object = Myinvocationhandler.bind (Realsubject);
    Subject Subject = (Subject) object;
  Subject.action (); }///dynamic proxy use interface subject{void action ()//proxy class Realsubject implements subject{@Override public void action () {System.out.println ("I am a proxy class, remember to execute me oh ....")
  "); The class Myinvocationhandler implements invocationhandler{object object;//the declaration of the object of the proxy class that implements the interface/** * Descrip Tion:① the object being instantiated ② returns a proxy class object * @param * @author Xiazhongwei * @data September 29, 2016: Afternoon 4:13:43 * @return * * Publ
    IC object Bind (object) {This.object = object; Return Proxy.newproxyinstance (Object.getclass (). GetclasSloader (), Object.getclass (). Getinterfaces (), this); /** * When a call to an overridden method is initiated by an object of the proxy class, it is converted to a call to the Invok method as follows */@Override public object Invoke (object proxy, methods meth
    OD, object[] args) throws Throwable {Object returnobject = Method.invoke (object, args);
  return returnobject;
 }
}

4. Dynamic Agent and AOP

Example One,

Package COM.ATGUIGU.SPRING.AOP;
 
Public interface Arithmeticcalculator {
  int i, int j);
  int sub (int i, int j);
   
  int mul (int i, int j);
  int div (int i, int j);
}
Package COM.ATGUIGU.SPRING.AOP;
 
Import org.springframework.stereotype.Component;
 
@Component ("Arithmeticcalculator") Public
class Arithmeticcalculatorimpl implements Arithmeticcalculator {
 
  @Override Public
  int Add (int i, int j) {
    int = i + j;
    return result;
  }
 
  @Override Public
  int sub (int i, int j) {
    int = i-j;
    return result;
  }
 
  @Override public
  int mul (int i, int j) {
    int = i * j;
    return result;
  }
 
  @Override Public
  int div (int i, int j) {
    int = i/j;
    return result;
  }
 

 Package COM.ATGUIGU.SPRING.AOP; public class Arithmeticcalculatorloggingimpl implements Arithmeticcalculator {@Override public int add (int i, Int j
    {System.out.println ("The method add begins with [" + i + "," + j + "]");
    int result = i + j;
    System.out.println ("The method add ends with" + result);
  return result; @Override public int sub (int i, int j) {System.out.println ("The method sub begins with [+ i +", "+ j +"] "
    );
    int result = I-j;
    System.out.println ("The method sub-ends with" + result);
  return result; @Override public int Mul (int i, int j) {System.out.println ("The method Mul begins with [+ i +", "+ j +"] "
    );
    int result = i * j;
    System.out.println ("The method Mul ends with" + result);
  return result; @Override public int div (int i, int j) {System.out.println ("The method Div begins with [" + i + "," + j + "]"
    );
    int result = i/j; System.out.println ("The Method Div ends with "+ result");
  return result;
  
 }
 
}
Package COM.ATGUIGU.SPRING.AOP;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Proxy;
 
Import Java.util.Arrays;
   
  public class Arithmeticcalculatorloggingproxy {//To proxy object private arithmeticcalculator target;
    Public Arithmeticcalculatorloggingproxy (Arithmeticcalculator target) {super ();
  This.target = target;
    }//Return proxy object public Arithmeticcalculator Getloggingproxy () {Arithmeticcalculator proxy = null;
    The proxy object has a class loader that is responsible for loading ClassLoader loader = Target.getclass (). getClassLoader ();
    The type of the proxy object, that is, which method Class [] interfaces = new Class[]{arithmeticcalculator.class}; When you call one of the proxy object's methods, execute the following code invocationhandler h = new Invocationhandler () {/** * Proxy: Agent object. You generally do not use this object * method: Methods that are being invoked * args: The arguments passed in by the calling method */@Override public object Invoke (object pr Oxy, method methods, object[] args) throws Throwable {//The proxy object is not called directly inside theMethod, Proxy.tostring () causes a dead loop to invoke the Invoke method String methodname = Method.getname ();
         
        Print log System.out.println ("[Before] the method" + methodname + "begins with" + arrays.aslist (args));
         
        Call target Method Object result = NULL;
          try {//predecessor notification result = Method.invoke (target, args);
          Returns a notification that can access the method's return value} catch (NullPointerException e) {e.printstacktrace (); Exception notification, you can access the exception that appears to the method//Post notification.
         
        Because the method can be an exception, the return value of the method is not accessed//the print log System.out.println ("[After] the" ("ends with" + result);
      return result;
     
    }
    };
     /** * Loader: Class loader used by the proxy object. * Interfaces: Specifies the type of proxy object.
     That is, what methods can be used in proxy proxy objects. * H: When specifically invoking the method of the proxy object, how to respond, in effect, is to invoke the Invocationhandler Invoke method */proxy = (arithmeticcalculator) PROXY.NEWPR
     
    Oxyinstance (loader, interfaces, h);
  return proxy;
  

 }
}
Package COM.ATGUIGU.SPRING.AOP;
 
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class Main {public
   
  static void Main (string[] args) {
    //Arithmeticcalculator arithmeticcalculator = new Ar Ithmeticcalculatorimpl ();
    Arithmeticcalculator arithmeticcalculator = new Arithmeticcalculatorloggingimpl ();
     
    Arithmeticcalculator = new Arithmeticcalculatorloggingproxy (arithmeticcalculator). Getloggingproxy ();
     
    int result = Arithmeticcalculator.add (one);
    SYSTEM.OUT.PRINTLN ("Result:" + result);
     
    result = Arithmeticcalculator.div (3);
    SYSTEM.OUT.PRINTLN ("Result:" + result);
     
  }
   

Example Two,

Package com.test.junit;
Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;
 
Import Java.lang.reflect.Proxy;
    public class Proxytest {public static void main (string[] args) {Realsubject realsubject = new Realsubject ();
    Myinvocationhandler Myinvocationhandler = new Myinvocationhandler ();
    Object object = Myinvocationhandler.bind (Realsubject);
    Subject Subject = (Subject) object;
  Subject.action (); }///dynamic proxy use interface subject{void action ()//proxy class Realsubject implements subject{@Override public void action () {System.out.println ("I am a proxy class, remember to execute me oh ....")
  "); The class Myinvocationhandler implements invocationhandler{object object;//the declaration of the object of the proxy class that implements the interface/** * Descrip Tion:① the object being instantiated ② returns a proxy class object * @param * @author Xiazhongwei * @data September 29, 2016: Afternoon 4:13:43 * @return * * Publ
    IC object Bind (object) {This.object = object; Return Proxy.newproxyinstance (Object.getclass (). GetclasSloader (), Object.getclass (). Getinterfaces (), this); /** * When a call to an overridden method is initiated by an object of the proxy class, it is converted to a call to the Invok method as follows */@Override public object Invoke (object proxy, methods meth
    OD, object[] args) throws Throwable {Object returnobject = Method.invoke (object, args);
  return returnobject;



 }
}

Thank you for reading this article, I hope to help you, thank you for your support for this site!

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.