javassist理解代码

package test;

/**
 * Created by IntelliJ IDEA.
 * Date: 11/06/23
 * Time: 10:48
 */
public class Day {
    private String id;


    public void showId(){
        this.setId("100");
        System.out.println("method : showId()" + this.id);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public static void main(String [] args) {
          System.out.println("method : showId()");
    }
}



package test;

import javassist.*;
import sun.text.normalizer.IntTrie;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * Date: 11/06/23
 * Time: 10:47
 * 
 */
public class TestRunMethod {

    /**
     * defineClass
     */
    protected static final String DEFINE_CLASS_METHOD_NAME = "defineClass";


    protected static final ProtectionDomain protectionDomain;

    /**
     * defineClass
     */
    protected static Method defineClassMethod;

    // static initializer
    static {

        protectionDomain = (ProtectionDomain) AccessController
                .doPrivileged(new PrivilegedAction() {
                    public Object run() {
                        return Day.class.getProtectionDomain();
                    }
                });

        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                final Class[] paramTypes = new Class[]{String.class,
                        byte[].class, int.class, int.class,
                        ProtectionDomain.class};
                try {
                    final Class loader = forName(ClassLoader.class
                            .getName());
                    defineClassMethod = loader.getDeclaredMethod(
                            DEFINE_CLASS_METHOD_NAME, paramTypes);
                    defineClassMethod.setAccessible(true);
                } catch (final NoSuchMethodException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });

    }

    /**
     *
     * @param className
     * @return {@link Class}
     * @see Class#forName(String)
     */

    public static Class forName(String className) {

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            return Class.forName(className, true, loader);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            return null;
        }
    }


    public static Class toClass(final ClassLoader classLoader, final CtClass ctClass) {
        try {

            final byte[] bytecode = ctClass.toBytecode();
			return (Class) defineClassMethod.invoke(classLoader, new Object[]{
							ctClass.getName(), bytecode, new Integer(0),
							new Integer(bytecode.length), protectionDomain});
        } catch (final CannotCompileException e) {
            e.printStackTrace();
        } catch (final IOException e) {
            e.printStackTrace();
        } catch (final IllegalAccessException e) {
            e.printStackTrace();
        } catch (final InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据字节码创建新方法,并对该方法做切面处理
     *
     * seasar2中是根据配置需要aop时,动态创建原有类的子类,并对需要切面的方法根据模板创建方法类,
	 * 方法类中关联各种advice,子类中调用该方法类的proceed方法和超类中的方法
     *
     * @param args
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException {
       // createClassByExitingClassFile();
        try {
            ClassPool cp = getClassPool();
            CtClass newDaysub = cp.getAndRename("test.Day", "NewDaysub");
            String bodyString = "public void getNumber(int num){System.out.println(\"num is \"+ num);}";
            addMethod(newDaysub, bodyString);
            CtMethod ctMethod = newDaysub.getDeclaredMethod("getNumber") ;
            ctMethod.insertBefore("System.out.println( \"before:\" +new java.util.Date( System.currentTimeMillis() ));");
            ctMethod.insertAfter("System.out.println( \"after:\" +new java.util.Date( System.currentTimeMillis() ));");
            Class clazz = toClass(cp.getClassLoader(), newDaysub);
            clazz.getMethod("getNumber", new Class[]{int.class}).invoke(clazz.newInstance(), new Object[]{new Integer(12)});
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (CannotCompileException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }


     private static void addMethod(CtClass ctClass, String bodyString){
         try {
             CtMethod n2 = null;//直接创建一个方法,带有一个int的参数和返回值
             n2 = CtNewMethod.make(bodyString, ctClass);
             ctClass.addMethod(n2);
         } catch (CannotCompileException e) {
             e.printStackTrace();
         }
     }

    /**
     * 根据己有的class字节码文件创建新的实例并运行
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     */
    private static void createClassByExitingClassFile() throws InvocationTargetException, NoSuchMethodException {
        try {
            ClassPool cp = getClassPool();
            CtClass newDaysub = cp.getAndRename("test.Day", "NewDaysub");
            executeMethod(cp, newDaysub);

        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建并设置加载路径
     * @return
     */
    private static ClassPool getClassPool() {
        ClassPool cp = ClassPool.getDefault();
        cp.insertClassPath(new ClassClassPath(TestRunMethod.class));
        return cp;
    }

    /**
     *
     * @param cp
     * @param newDaysub
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws InstantiationException
     */
    private static void executeMethod(ClassPool cp, CtClass newDaysub) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException {
        Class clazz = toClass(cp.getClassLoader(), newDaysub);
        clazz.getMethod("showId",null).invoke(clazz.newInstance(),null);
    }


    //动态创建子类
    private static void createNewSubClass(ClassPool cp) throws CannotCompileException, NotFoundException, IOException {
        CtClass day = cp.makeClass("test.DaySub");
        day.setSuperclass(cp.get("test.Day"));
        printCtClassFile(day);
    }


    //写入字节码(calss格式)文件
    private static void printCtClassFile(CtClass day) throws CannotCompileException, IOException {
        //System.out.println(day.toClass());
        day.writeFile("D:\\IntelliJ IDEA 10.5\\workspace\\javassist-3.14.0-GA\\target\\classes");
    }


}

你可能感兴趣的:(AOP,thread,Security,sun,idea)