Dynamically generating classes in memory using Javaassist __java

Source: Internet
Author: User
"The General directory >>>" | "project Source >>>"

Javassist is an Open-source class library for parsing, editing, and creating Java bytecode. was created by Shigeru Chiba (Thousand Yezi) of the Mathematics and Computer Science Department of the Tokyo University of Technology. It has joined the open source JBoss Application Server project to implement a dynamic "AOP" framework for JBoss by using javassist for bytecode operations.

Now let's learn how to use Javaassist.

Package wjc.javaassist;

Import javassist.*;
Import Java.lang.reflect.Method;

Import Java.net.URLDecoder; /** * <pre> * Test javaassist Direct operation of Java bytecode files * </pre> * Author: Wang Junshu * date:2018-02-21 22:21 * blog:http:
 BLOG.CSDN.NET/DERRANTCM * Github:https://github.com/wang-jun-chao * all Rights Reserved!!! */public class Classgeneration {public static void main (string[] args) {Classpool pool = Classpool.getdefau
        Lt ();

        Ctclass cc = Pool.makeclass ("Wjc.javaassist.bean.Boss");
            try {Ctfield f1 = ctfield.make ("private int id;", cc);
            Ctfield F2 = ctfield.make ("Private String name;", CC);

            Ctfield F3 = Ctfield.make ("private int age;", CC);
            Cc.addfield (F1);
            Cc.addfield (F2);

            Cc.addfield (F3);
            Ctmethod m1 = Ctmethod.make ("public int getId () {return id;}", CC);
            Ctmethod m2 = ctmethod.make ("public void setId (int id) {$0.id=$1;}", CC); Cc.addmEthod (M1);

            Cc.addmethod (m2);
            Ctmethod m3 = ctmethod.make ("Public String GetName () {return name;}", CC);
            Ctmethod M4 = Ctmethod.make ("public void SetName (String name) {$0.name=$1;}", CC);
            Cc.addmethod (m3);


            Cc.addmethod (M4);
            Parameterless Construction constructor Ctconstructor Constructor1 = new Ctconstructor (New ctclass[]{}, CC); Constructor1.setbody ("{$0.id=1; $0.name=\ "Wjc\";
            $0.age=20;} ");


            Cc.addconstructor (Constructor1); A parameter constructor ctconstructor Constructor2 = new Ctconstructor (new Ctclass[]{ctclass.inttype, Pool.get ("Java.lang.St
            Ring "), Ctclass.inttype}, CC);
            Constructor2.setbody ("{$0.id=$1;$0.name=$2;$0.age=$3;}");



            Cc.addconstructor (CONSTRUCTOR2);
            Takes the root path of the current application run String path = ClassGeneration.class.getClassLoader (). GetResource (""). GetPath (); Path = Path.contains (":")?
            Path.substring (1): path; Path = URldecoder.decode (Path, "Utf-8");

            Class is generated to the root path under cc.writefile (path); Create a parameterless instance through reflection and fetch the EM method///To prevent the compiler from making an error, use the O Declaration and keep using Object o = Class.forName ("Wjc.javaassist.bean.Boss
            "). newinstance ();
            Method getter = O.getclass (). GetMethod ("GetName");

        System.out.println (Getter.invoke (o));
        catch (Exception e) {e.printstacktrace ();
 }

    }
}

Run Result:

Generated classes

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.