java原始代码:
publicvoidthrowableCaught(Stringinput)throwsSQLException,TimeoutException{
if(input.equals("1"))
thrownewSQLException();
elseif(input.equals("2"))
thrownewTimeoutException();
elseif(input.equals("3"))
{
try
{
inti=1;
intj=0;
System.out.println(j);
j=i/j;
}
catch(Exceptione)
{
e.printStackTrace();
}
}
}
希望通过asm修改字节码将原始代码变成:
publicvoidthrowableCaught(Stringinput)throwsSQLException,TimeoutException
{
if(input.equals("1")){
SQLExceptionlocalSQLException=newSQLException();
ThrowablelocalThrowable1=(Throwable)localSQLException;
System.out.println(localThrowable1);
throwlocalSQLException;
}if(input.equals("2")){
TimeoutExceptionlocalTimeoutException=newTimeoutException();
ThrowablelocalThrowable2=(Throwable)localTimeoutException;
System.out.println(localThrowable2);
throwlocalTimeoutException;
}
}
如果将原始代码中的input.equals("3")那块屏蔽,asm修改后可以得到上面的代码;
如果不屏蔽input.equals("3")那块,结果是:
publicvoidthrowableCaught(Stringinput)throwsSQLException,TimeoutException
{
if(input.equals("1")){
SQLExceptionlocalSQLException=newSQLException();
ThrowablelocalThrowable1=(Throwable)localSQLException;
System.out.println(localThrowable1);
throwlocalSQLException;
}if(input.equals("2"))
{
TimeoutExceptionlocalTimeoutException;//----------这里没有实例化了--------------
ThrowablelocalThrowable2=(Throwable)localTimeoutException;
System.out.println(localThrowable2);
throwlocalTimeoutException;
}
inti=1;
intj=0;
System.out.println(j);
j=i/j;
}
asm代码:
publicclassDBMethodAdaptorextendsAdviceAdapter{
......
@Override
publicvoidvisitInsn(intopcode){
if(opcode==Opcodes.ATHROW){
//gettheThrowableobjectoffthestack
mv.visitInsn(Opcodes.DUP);
intexceptionVar=newLocal(Type.getType(Throwable.class));
mv.visitVarInsn(Opcodes.ASTORE,exceptionVar);
mv.visitVarInsn(Opcodes.ALOAD,exceptionVar);
mv.visitTypeInsn(Opcodes.CHECKCAST,"java/lang/Throwable");
intexceptionVar2=newLocal(Type.getType(Throwable.class));
mv.visitVarInsn(Opcodes.ASTORE,exceptionVar2);
mv.visitFieldInsn(GETSTATIC,"java/lang/System","out","Ljava/io/PrintStream;");
mv.visitVarInsn(ALOAD,exceptionVar2);
mv.visitMethodInsn(INVOKEVIRTUAL,"java/io/PrintStream","println","(Ljava/lang/Object;)V",false);
mv.visitVarInsn(ALOAD,exceptionVar);
}
mv.visitInsn(opcode);
}
@Override
publicvoidvisitMaxs(intmaxStack,intmaxLocals){
mv.visitMaxs(0,0);//COMPUTE_MAXS自动计算
}
}
分 -->
|