First, the code generation example
The Javac command in Java is the "ancestor" of bytecode generation, and it is also written in Java. There is also a JSP compiler in the Web, an AOP framework that is embedded at compile time, and a very common dynamic proxy, and even the JVM may generate bytecode at run time to speed up when it is reflected.
If you use spring for bean management, you use dynamic proxies, because if the bean is interface-oriented programming, the bean is enhanced by dynamic proxy methods within spring.
Ii. examples
Package Com.company;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import java.lang.reflect.proxy;/** * Created by LSJ on 2015/9/6. * Dynamic Agent Advantage: * Not to write less code, but to, * in the original class and interface is unknown, determine proxy class agent behavior, that is, the proxy class and the original class * out of direct contact */public class Dynamicproxytest {interface Ihello {void SayHello (); } Static class Hello implements ihello{@Override public void SayHello () {System.out.printl N ("Hello World"); }} Static Class Dynamicproxy implements invocationhandler{Object oriobj; Object bind (Object oriobj) {this.oriobj = Oriobj; Return Proxy.newproxyinstance (Oriobj.getclass (). getClassLoader (), Oriobj.getclass (). getinterfaces (), th IS); } @Override public object invoke (object proxy, Method method, object[] args) throws Throwable {S Ystem.out.println ("Welcome"); Return Method.invoke (oriobj, args); return nulL }} public static void Main (String [] args) {/** * Returns an object that implements the Ihello interface and proxies the behavior of the new Hello () instance, validates, optimizes, etc. * Generated bytecode, and the class was explicitly loaded */Ihello Hello = (ihello) new Dynamicproxy (). bind (New Hello ()); Hello.sayhello (); }}
Results:
Welcome
Hello World
Java bytecode generation and implementation of dynamic proxy