我是靠谱客的博主 激昂大雁,最近开发中收集的这篇文章主要介绍java asm生成if判断,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

asm使用if判断

package club.jiajia.test3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class TestAsm2 implements Opcodes{
	public static void main(String[] args) throws InstantiationException, IllegalAccessException{
		ClassWriter cw=new ClassWriter(0);
		String className="Example2";
		cw.visit(0x31,ACC_PUBLIC,className,null,"java/lang/Object",new String[]{"java/lang/Cloneable",ITest.class.getName().replace('.','/')});

		String a="a";
		Object av=123;
		
		String getA="getA";
		String setA="setA";
		cw.visitField(ACC_PRIVATE,a,"I",null,av == null?null:Integer.parseInt(av.toString())).visitEnd();

		
		MethodVisitor mv=cw.visitMethod(ACC_PUBLIC,getA,"()I",null,null);
		mv.visitCode();
		mv.visitVarInsn(ALOAD,0);
		mv.visitFieldInsn(GETFIELD,className,a,"I");
		mv.visitInsn(IRETURN);
		mv.visitMaxs(2,2);
		mv.visitEnd();
		cw.visitEnd();
		
		
		/***********************************************************/
		mv=cw.visitMethod(ACC_PUBLIC,setA,"(I)V",null,null);
		mv.visitCode();
		mv.visitVarInsn(ILOAD, 1);
		Label label = new Label();
		mv.visitJumpInsn(IFLT, label);
		mv.visitVarInsn(ALOAD, 0);
		mv.visitVarInsn(ILOAD, 1);
		mv.visitFieldInsn(PUTFIELD, className, "a", "I");
		Label end = new Label();
		mv.visitJumpInsn(GOTO, end);
		mv.visitLabel(label);
		mv.visitLabel(end);
		mv.visitInsn(RETURN);
		mv.visitMaxs(2, 2);
		mv.visitEnd();
		/***********************************************************/
		
		
		//下面产生构造方法
		mv=cw.visitMethod(ACC_PUBLIC,"<init>","()V",null,null);
		mv.visitCode();
		mv.visitVarInsn(ALOAD,0);
		mv.visitMethodInsn(INVOKESPECIAL,"java/lang/Object","<init>","()V");
		mv.visitInsn(RETURN);
		mv.visitMaxs(1,1);
		mv.visitEnd();
		
		
		cw.visitEnd();

		byte[] bs=cw.toByteArray();
		File file = new File("E://jiajiajia/Example2.class");
		try {
			FileOutputStream fout = new FileOutputStream(file);
			fout.write(bs);
			fout.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		MyCLassLoader loader=new MyCLassLoader();
		Class<?> c=loader.defineClass(bs);
		
		ITest ins=(ITest)c.newInstance();
		ins.setA(10);
		System.out.println(ins.getA());
	}
	
	public interface ITest{
		public int getA();
		public void setA(int a);
	}

	public static class MyCLassLoader extends ClassLoader{
		public Class<?> defineClass(byte[] data){
			return super.defineClass(null,data,0,data.length,null);
		}
	}
}

 

最后

以上就是激昂大雁为你收集整理的java asm生成if判断的全部内容,希望文章能够帮你解决java asm生成if判断所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部