Framework programming under Java (reflection, generics, meta-data, CGLib, code Dynamics, AOP, Dynamic language embedding)

Source: Internet
Author: User
Tags throwable


Although Java does not have the dynamic language like the violence, but still days, water to produce many framework technology---reflection (reflection), generics (generics), meta-data (annotation), proxies (proxy/cglib), Code dynamic Generation ( ASM), AOP (AspectJ), Dynamic language embedding (Groovy/javascript/beanshell). In the face of these, we like the overnight rich farmers, a little helpless look.

Reflection is a technique that allows the framework to invoke object properties and functions based on "information that exists as a string," one of the biggest advances in Java for C + +---making framework programming truly civilian. MFC years, no matter how Houtie, but still in college I just don't understand those registered "message-function mapping" magic macros.

However, the reflection of Java is very proud of C + +, because C#,ruby,python and even PHP have the function of reflection as standard. Moreover, the reflection grammar of others is embedded in the base object class, with the weakest PHP to see:

$func _name= "HelloWorld";
$foo, $func _name;

and Java, but got out of class,methed, field,constructor so a lot of class out. Originally this is the Java designer very rigorous, very cool embodiment, the problem is that it actually does not provide an integrated simple way of writing ... The same scenario also appears in the Java I/O class library.
Microsoft is doing a better job of trying to please developers.

Because of the ruthless Java, we have to make the project to self-made beanutils. Fortunately Apache Jakarta Commons has done a better, can directly use-previously written introduction article.
In addition spring also made one.

Idle to do nothing, can also emule a 〈relection in action〉 back to see.

and C + + under the "reflection", see my Idol di article. There is also a comparison of the BT C + + framework called ACDK, the whole of itself and Java very much like, there is reflection and garbage collection, and even jsdk the same thread, UNICODE,I/O, network, XML API. Unfortunately, even in the c++0x, Uncle B is not ready to support reflection at the language level.

Reflection, proxy, and metadata are the strongest three features in Java, plus cglib (Code Generation Library) and ASM, which makes Java not Ruby,python alitily, but can make a powerful framework.
Proxy can be regarded as a micro-AOP, understand that provides a third code in the inheritance and delegation outside the package path, as long as there is enough imagination, can do very fun, spring's source code with proxy is used very casually, I am very jealous. Unfortunately proxy must be based on an interface. So spring's approach, based on the interface of the proxy, otherwise it will be used cglib. AOP, the general trifle non-compoent level of not trouble AspectJ shot.

Cglib of the enhancer said magic, use up a page of paper is finished.
Its principle is to use enhancer to generate a subclass of the original class, and set the callback to proxy, the original class of each method call will be called to implement the Methodinterceptor interface proxy intercept () function:

public Object Intercept (object O,method method,object[] Args,methodproxy proxy)


In the Intercept () function, you can perform an object Result=proxy.invokesuper (O,args), execute the original function, add your own things before and after the execution, change its parameter values, or you can cheat and completely do anything else. Plainly, it is the around advice in AOP.

AOP did not appear before, the domain classic design pattern is decorator, like Java IO Stream design is so. However, if for each DAO, the write decorator function of each method will write dead, so the advantage of using Cglib is to intercept all methods at once.


In addition, cglib in addition to enhancer, there are bulkbean and transform, are Hibernate persistent Foundation, but the document is poor, for a while not to see how to use.

1.AOP 100 times 100 times the log aspect in Cglib is doing this:


public class Logdaoproxy implements Methodinterceptor
{
Private Logger Log=logger.getlogger (Logdaoproxy.class);
Private enhancer enhancer=new enhancer ();
Returns the subclass of DAO
Public Object Getdao (Class clz)
{
Enhancer.setsuperclass (CLZ);
Enhancer.setcallback (this);
return Enhancer.create ();
}
The default interception method
public Object Intercept (object O,method method,object[] Args,methodproxy proxy) throws Throwable
{
Log.info ("Call log Method" +method.getname ());
Object Result=proxy.invokesuper (O,args);
return result;
}
}


Code for the application:

Logdaoproxy proxy = new Logdaoproxy ();
Goodsdao DAO = (Goodsdao) Proxy.getdao (Goodsdao.class);
Dao.insert (goods);


2. The advanced decorator that should be slightly modified under the management of Spring
The above example uses return Enhancer.create (); Create subclass instances, but under spring management, some bean instances must be created and managed by spring rather than created by enhancer. So I slightly modified the above usage, so that it really as a proxy role, please compare the part of the bold word


public class Logdaoproxy implements Methodinterceptor
{
Private Logger Log=logger.getlogger (Logdaoproxy.class);
   Private Object Dao=null ;
Private enhancer enhancer=new enhancer ();
Returns the subclass of DAO
Public Object Getdao (Class clz,object dao)
{
This.dao = DAO;
Enhancer.setsuperclass (CLZ);
Enhancer.setcallback (this);
return Enhancer.create ();
}
The default interception method
public Object Intercept (object O,method method,object[] Args,methodproxy proxy) throws Throwable
{
Log.info ("Call log Method" +method.getname ());
Object Result = proxy.invoke (DAO, args);
return result;
}
}


It can be seen that the DAO was created by enhancer in the original mode at Getdao (), and the DAO created by enhancer is returned with the object o parameter when calling intercept.
In the new mode, DAO is passed out from the outside in Getdao (), and Enhancer.create () returns a proxy. When intercept is called, it actually operates with the DAO that was previously passed in, ignoring the proxy passed in by the object o parameter.

A little pity, the Intercept function Methodproxy signature is fixed, that is, if the customer calls Foo (String), you can not use Proxy.invoke stolen foo (string,string);

Framework programming under Java (reflection, generics, meta-data, CGLib, code Dynamics, AOP, Dynamic language embedding)

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.