8.11.12

Read Field Values using ASM

http://mushiqianmeng.blog.51cto.com/3970029/843578

This is a very good post in Chinese to talk about the entrance level information of ASM and Java bytecode. I change the code slightly so that I have better output and use JUnit to drive the the output.

Here is the code

 @Test
 public void testMethodA() throws Exception {
  ClassReader reader = new ClassReader("foo.ForReadClass");
  ClassNode cn = new ClassNode();
  reader.accept(cn, 0);
  System.out.println(cn.name);
  @SuppressWarnings("unchecked")
  List<fieldnode> fields = cn.fields;
  printFieldNodes(fields);
 }

 private void printFieldNodes(List<fieldnode> fieldList) {
  for(FieldNode fieldNode : fieldList) {
   System.out.printf("Field name=%s, desc=%s, value=%s, access=%d\n",
     fieldNode.name,
     fieldNode.desc,
     fieldNode.value,
     fieldNode.access);
   if(fieldNode.visibleAnnotations != null) {
    for(Object anNode : fieldNode.visibleAnnotations) {
     System.out.println(((AnnotationNode)anNode).desc);
    }
    
   }
  }
 }
 
 @Test
 public void testMethodA2() throws Exception {
  ClassReader reader = new ClassReader(foo.ForReadClass.class.getName());
  ClassNode cn = new ClassNode();
  reader.accept(cn, 0);
  @SuppressWarnings("unchecked")
  List<methodnode> methodList = cn.methods;
  for(MethodNode md : methodList)
  {
   System.out.printf("Method Node name = %s, access = %d, desc = %s, signature = %s\n",
     md.name,
     md.access,
     md.desc,
     md.signature);

   @SuppressWarnings("unchecked")
   List<localvariablenode> lvNodeList = md.localVariables;
   for(LocalVariableNode lvn : lvNodeList) {
    System.out.printf("\tLocal Variable name = %s, label = %s, desc = %s, sign = %s\n",
      lvn.name,
      lvn.start.getLabel(),
      lvn.desc,
      lvn.signature);
   }
   
   @SuppressWarnings("unchecked")
   Iterator<abstractinsnnode< instraIter = md.instructions.iterator();
   while(instraIter.hasNext()) {
    AbstractInsnNode abi = instraIter.next();
    if(abi instanceof LdcInsnNode) {
     LdcInsnNode ldcI = (LdcInsnNode) abi;
     System.out.println("\tLDC node value : " + ldcI.cst);
    }
   }
  }
  
  MethodVisitor mv = cn.visitMethod(Opcodes.AALOAD, "<init>", Type.getType(String.class).toString(), null, null);
  mv.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(String.class), "str", Type.getType(String.class).toString());
  System.out.println(cn.name);
  @SuppressWarnings("unchecked")
  List<fieldnode> fieldList = cn.fields;
  printFieldNodes(fieldList);
 }
hello world

No comments: