Java Dynamic proxy Implementation & Dynamic bytecode generation (ASM)

Source: Internet
Author: User
The current Java development package includes support for dynamic proxies, but its implementation only supports the implementation of interfaces. The main implementation is through the java. Lang. Reflect. proxy class and Java. Lang. Reflect. invocationhandler interface. The proxy class is mainly used to obtain dynamic proxy objects. The invocationhandler interface is used to constrain the implementation of callers. The following describes the business methods defined by the helloworld interface. helloworldimpl is the implementation of the helloworld interface and helloworldhandler is the implementation of the invo. The Code is as follows: business interface:

Public interface helloworld {void sayhelloworld ();}
Business interface implementation:

Public class helloworldimpl implements helloworld {

Public void sayhelloworld () {system. Out. println ("Hello world! ");}}

 

To implement invocationhandler, you need to add a processing job before and after the interface method call. Here, only two strings are output to the background before and after the method call. The Code is as follows:

Import java. Lang. Reflect. invocationhandler; import java. Lang. Reflect. method;

Public class helloworldhandler implements invocationhandler {// the original object private object objoriginal to be proxy;/*** constructor. * @ Param OBJ refers to the original object to be proxy. */Public helloworldhandler (Object OBJ) {This. objoriginal = OBJ ;}

Public object invoke (Object proxy, method, object [] ARGs) throws throwable {object result; // dobefore () before the method is called (); // call the Method Result = method of the original object. invoke (this. objoriginal, argS); // doafter (); return result;} private void dobefore () {system. out. println ("before method invoke! ");} Private void doafter () {system. Out. println (" after method invoke! ");}}

 

 

Test code:

Import java. Lang. Reflect. invocationhandler; import java. Lang. Reflect. proxy;

Public class test {

Public static void main (string [] ARGs ){

Helloworld hW = new helloworldimpl (); invocationhandler handler = new helloworldhandler (HW); helloworld proxy = (helloworld) proxy. newproxyinstance (HW. getclass (). getclassloader (), HW. getclass (). getinterfaces (), Handler );

Proxy. sayhelloworld ();}}

 

 

 

 

Ø first, obtain the implementation object of a business interface; ø obtain an invocationhandler implementation, which is the helloworldhandler object; ø create a dynamic proxy object; ø call the sayhelloworld () method through a dynamic proxy object, at this time, the original object helloworldimpl. the sayhelloworld () method outputs two strings. The output of the running test class is as follows:

Before method invoke! Hello world! After method invoke!
There are many method call codes in the test class. In our actual application, we can use the configuration file to simplify the client call implementation. In addition, you can use dynamic proxies to implement simple AOP.
========================================================== ================================
Dynamic bytecode generation (ASM)

Guidance:
Hello world written in ASM. Search for articles related to ASM on the Internet, and finally retrieve matrix .. Khan

Introduction to the asm2.0 bytecode framework

Http://www.matrix.org.cn/resource/article/2006-02-20/ASM+Bytecode+Framework_44220.html

Package my;

Import java. Lang. Reflect. method;

Import org. objectweb. ASM. classwriter;
Import org. objectweb. ASM. methodvisitor;
Import org. objectweb. ASM. Opcodes;

Public class Hello {
@ Suppresswarnings ("unchecked ")
Public static void main (string [] ARGs) throws exception {

Classwriter CW = new classwriter (classwriter. compute_maxs );
// Class access start: Required
CW. Visit (Opcodes. vswitches 5, Opcodes. acc_public, "My/foo", null, "Java/lang/object", null );

// Provide at least one Constructor
Methodvisitor mv = CW. visitmethod (Opcodes. acc_public ," "," () V ", null, null );
// Code start: Required
MV. visitcode ();
MV. visitvarinsn (Opcodes. aload, 0 );
MV. visitmethodinsn (Opcodes. invokespecial, "Java/lang/object "," "," () V ");
MV. visitinsn (Opcodes. Return );
// Maximum space of the computing stack and local variables: Required
MV. visitmaxs (0, 0 );
// Code ended: Required
MV. visitend ();

MV = CW. visitmethod (Opcodes. acc_public | Opcodes. acc_static, "Main ",
"([Ljava/lang/string;) V", null, null );
MV. visitcode ();
MV. visitfieldinsn (Opcodes. getstatic, "Java/lang/system", "out", "ljava/IO/printstream ;");
MV. visitldcinsn ("Hello world! ");
MV. visitmethodinsn (Opcodes. invokevirtual, "Java/IO/printstream", "println ",
"(Ljava/lang/string;) V ");
MV. visitinsn (Opcodes. Return );
MV. visitmaxs (0, 0 );
MV. visitend ();

// Class end: Required
CW. visitend ();

Final byte [] BS = CW. tobytearray ();
Class clazz = new classloader (){
Protected class> findclass (string name) throws classnotfoundexception {
Return defineclass (name, BS, 0, BS. Length );
}
}. Loadclass ("My. foo ");
Method method = clazz. getmethod ("Main", new class [] {string []. Class });
// The method of array parameters. The reflection call method looks odd.
Method. Invoke (null, (object) New String [0]);

For (INT I = 0; I <BS. length; I ++)
System. Out. printf ("% d: \ t % 02x \ t % C \ n", I, BS [I], (char) BS [I]);

// Outputstream out = new fileoutputstream ("D:/My/Foo. Class ");
// Out. Write (BS );
// Out. Close ();
}
}
Using ASM to write an aqua data Studio 6.0 cracking:

The procedure is simple:
1. Find the method for determining the license and modify the code to make the total return true
2. Kill one license thread.

Copy the JAR file to the installation directory and modify the last line of the datastudio. BAT file:
Java-javaagent: ads. Crack. jar-CP ". \ Lib \ ads. jar; % ads_path %" com. aquafold. datastudio. datastudio

Because the Forum does not support uploading jar files, you can change the file extension to ads. Crack. jar.

Ads.crack.jar.zip

Sometimes, if you want to get all the instances of a class in the program, you can also use ASM to modify the code:

Package my;

Import java. Io. fileoutputstream;
Import java. Io. outputstream;
Import java. Lang. Reflect. field;
Import java.net. url;
Import java. util. List;

Import org. objectweb. ASM. classadapter;
Import org. objectweb. ASM. classreader;
Import org. objectweb. ASM. classvisitor;
Import org. objectweb. ASM. classwriter;
Import org. objectweb. ASM. methodadapter;
Import org. objectweb. ASM. methodvisitor;
Import org. objectweb. ASM. Opcodes;

Public class hellomodifyasm {
Public static void main (string [] ARGs) throws exception {
URL url = hellomodifyasm. Class. getresource ("foo. Class ");
Classwriter CW = new classwriter (classwriter. compute_maxs );
Classvisitor CV = new classadapter (CW ){

Public void visit (INT version, int access, string name, string signature,
String supername, string [] interfaces ){
Super. Visit (version, access, name, signature, supername, interfaces );

// Add the field: public static LIST _ my_instances;
Super. visitfield (Opcodes. acc_public | Opcodes. acc_static, "_ my_instances ",
"Ljava/util/list;", null, null );

// Add a static initialization Block
Methodvisitor mv = super. visitmethod (Opcodes. acc_static ," "," () V ", null, null );
MV. visitcode ();
MV. visittypeinsn (Opcodes. New, "Java/util/arraylist ");
MV. visitinsn (Opcodes. DUP );
MV. visitmethodinsn (Opcodes. invokespecial, "Java/util/arraylist "," "," () V ");
MV. visitfieldinsn (Opcodes. putstatic, "My/foo", "_ my_instances", "ljava/util/list ;");
MV. visitinsn (Opcodes. Return );
MV. visitmaxs (0, 0 );
MV. visitend ();
}

Public methodvisitor visitmethod (INT access, string name, string DESC,
String signature, string [] exceptions ){
Methodvisitor mv = super. visitmethod (access, name, DESC, signature, exceptions );

// Modify the constructors without parameters:
If (! " ". Equals (name) |! "() V". Equals (DESC ))
Return mV;
Return new methodadapter (MV ){

Public void visitinsn (INT opcode ){
If (opcode = Opcodes. Return ){
Visitfieldinsn (Opcodes. getstatic, "My/foo", "_ my_instances ",
"Ljava/util/list ;");
Visitvarinsn (Opcodes. aload, 0 );
Visitmethodinsn (Opcodes. invokeinterface, "Java/util/list", "add ",
"(Ljava/lang/object;) z ");
}
Super. visitinsn (opcode );
}
};
}
};

Classreader Cr = new classreader (URL. openstream ());
Cr. Accept (CV, classreader. skip_debug );
Final byte [] BS = CW. tobytearray ();

Outputstream out = new fileoutputstream ("D:/My/Foo. Class ");
Out. Write (BS );
Out. Close ();

Class> clazz = new classloader (null ){
Public class> findclass (string name) throws classnotfoundexception {
If (! "My. foo". Equals (name ))
Return classloader. getsystemclassloader (). loadclass (name );
Return defineclass (name, BS, 0, BS. Length );
}
}. Loadclass ("My. foo ");
Clazz. newinstance ();
Clazz. newinstance ();

Field field = clazz. getfield ("_ my_instances ");
List instances = (list) field. Get (null );
System. Out. println (instances. Size ());
For (Object OBJ: instances ){
System. Out. println (OBJ );
}
}
}

Problem: if the original class has or does not have a static initialization block, the processing method is different.
After thinking about it, you may be able to set the flag in the visitmethod method, and then add the flag in the visitend method (for the absence of the Flag ).
In addition, if there are multiple constructors, how can we ensure that the inserted code will not be executed repeatedly?
Even if you want to insert a statement into the original code, the search for the Insert Location is also quite costly (you need to find the bytecode of different return statements)

Hellomodifyasm. Java

This article is transferred from
Http://www.matrix.org.cn/thread.shtml? Topicid = edd2d10c-a79a-11db-8440-755941c7293d & forumid = 1

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.