ASMSupport教程4.10 instanceof操作符生成

instanceof是判断对象是否是某种类型的,我们可以看下下面的代码:

package generated.operators;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class InstanceofOperatorGenerateExample
{
public static void main(String[] args)
{

System.out.println("String" instanceof CharSequence);
System.out.println(new ArrayList() instanceof List);
System.out.println(new HashMap() instanceof List);

}
}

我们知道,这段代码打印出来的是

true

true

false

下面我们用ASMSupport生成上面的代码

package example.operators;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import jw.asmsupport.block.method.common.StaticMethodBody;
import jw.asmsupport.clazz.AClass;
import jw.asmsupport.clazz.AClassFactory;
import jw.asmsupport.creator.ClassCreator;
import jw.asmsupport.definition.value.Value;
import jw.asmsupport.definition.variable.LocalVariable;

import org.objectweb.asm.Opcodes;

import example.AbstractExample;

public class InstanceofOperatorGenerate1 extends AbstractExample {



    public static void main(String[] args) {

        ClassCreator creator = new ClassCreator(Opcodes.V1_5, Opcodes.ACC_PUBLIC , "generated.operators.InstanceofOperatorGenerateExample", null, null);

        /*
         * 生成一个main方法
         */
        creator.createStaticMethod("main", new AClass[]{AClassFactory.getProductClass(String[].class)}, new String[]{"args"}, null, null,
                Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, new StaticMethodBody(){

            @Override
            public void generateBody(LocalVariable... argus) {
                invoke(systemOut, "println", instanceOf(Value.value("String"), AClassFactory.getProductClass(CharSequence.class)));
                invoke(systemOut, "println", instanceOf(invokeConstructor(AClassFactory.getProductClass(ArrayList.class)),
                        AClassFactory.getProductClass(List.class)));
                invoke(systemOut, "println", instanceOf(invokeConstructor(AClassFactory.getProductClass(HashMap.class)),
                        AClassFactory.getProductClass(List.class)));
                runReturn();
            }
        });
        generate(creator);
    }

}

这里面instanceof操作对于的方法是instanceOf,具体如下:

jw.asmsupport.block.ProgramBlock.instanceOf(Parameterized obj, AClass type) ,这个方法有两个参数:

  1. instanceof左边的参数,是一个对象。
  2. AClass类型,instanceof右边的参数。

AClass是ASMSupport的特有的类型,详细可以见博客ASMSupport教程1之动态生成接口。

执行这段代码,也是:

true

true

false

你可能感兴趣的:(java,字节码,ASM,ASMSupport)