ASMSupport教程4.2

本文介绍如何使用ASMSupport生成带有返回值及无返回值的方法,并通过具体示例代码展示了如何实现这些方法。

<h2>4.2 生成Return操作</h2> <p>这一节我们将讲述如何生成return操作,我们将生成如下代码:</p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:0041272d-4ecf-4039-a991-b5323856859d" class="wlWriterEditableSmartContent"><pre class="brush: java; gutter: true; first-line: 1; tab-size: 4; toolbar: true; width: 964px; height: 263px;" style=" width: 964px; height: 263px;overflow: auto;">package generated.operators;

import java.io.PrintStream;

public class ReturnOperatorGenerateExample { public static String commonMethod() { return "I'm from commonMethod"; }

public static void main(String[] args) { System.out.println(commonMethod()); } }</pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>

<p>这段代码的两个方法的返回类型分别是String和void,对应的ASMSupport的代码如下:</p>

<p> <div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9D7513F9-C04C-4721-824A-2B34F0212519:74055c8b-f8a1-4671-a4d4-5f47171f957e" class="wlWriterEditableSmartContent"><pre class="brush: java; gutter: true; first-line: 1; tab-size: 4; toolbar: true; width: 964px; height: 471px;" style=" width: 964px; height: 471px;overflow: auto;">public static void main(String[] args) { ClassCreator creator = new ClassCreator(Opcodes.V1_5, Opcodes.ACC_PUBLIC , &quot;generated.operators.ReturnOperatorGenerateExample&quot;, null, null);

/* 
 * 有返回类型的方法
 */
creator.createStaticMethod(&quot;commonMethod&quot;, null, null, AClass.STRING_ACLASS, null, Opcodes.ACC_PUBLIC, new StaticMethodBody(){
	@Override
	public void generateBody(LocalVariable... argus) {
		runReturn(Value.value(&quot;I'm from commonMethod&quot;));
	}
});
	
/* 
 * 无返回类型的方法
 */
creator.createStaticMethod(&quot;main&quot;, new AClass[]{AClassFactory.getProductClass(String[].class)}, new String[]{&quot;args&quot;}, null, null,
		Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, new StaticMethodBody(){
	@Override
	public void generateBody(LocalVariable... argus) {
		invoke(systemOut, &quot;println&quot;, invokeStatic(getMethodOwner(), &quot;commonMethod&quot;));
		runReturn();
	}
});
generate(creator);

}</pre><!-- Code inserted with Steve Dunn's Windows Live Writer Code Formatter Plugin. http://dunnhq.com --></div>

</p>

<p>这里我们主要关注的是runReturn(Value.value(&quot;I'm from commonMethod&quot;))和runReturn(),前者是非void的,参数就是我们方法需要返回的值,后者就是直接return,没有返回值。</p>

转载于:https://my.oschina.net/wensiqun/blog/140070

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值