2 Replies Latest reply on Jun 7, 2010 10:15 AM by xeoshow

    How can get the initial member field value?

      Hello, dear all

       

      I want to get the initial member field value via javassist, can that be achived?

       

      For example, sample class as below. I just want exactly get the 2 for x, 3 for y, and "world" for str, and "hello" for s, and the string "new HashMap()" for hashMap (not the result of  new HashMap(), just the string "new HashMap()"). Can this be done via javassist? Thanks a lot.

       

      ---------------------------------

      public class Point {
          static int x = 2;
          int y = 3;
          static String str = "world";

          String s = "hello";
          HashMap hashMap = new HashMap();

       

          void move(int m, int n) {
              x = x + m;
              y += n;
              hashMap.put("name", "hashmap");
          }

       

      }

        • 1. Re: How can get the initial member field value?
          swd847

          This stuff is set in the constructor, so some of it can be extracted, probably not it the format you want though.

           

          For integer fields the bytecode code that gets generated would look something like:

           

          ALOAD_0 //put the this pointer on the stack

          ICONST_2 //put the integer constant 2 on the stack

          PUTFIELD com/mydomain/Point.x //set the field value.

           

          The hashmap field would be slightly more complex:

           

          ALOAD_0 //put the this pointer on the stack

          ANEW java/util/HashMap //create the hashmap instance

          DUP //duplicate it so it is still on the stack after the constructor call

          INVOKESPECIAL java/util/HashMap.<init> //call the constructor

          PUTFIELD com/mydomain/Point.hashMap //set the field value.

           

           

          To actually extract this information you would need to write some kind of bytecode analyser, and even then there would be cases that it could not handle correctly, as you would also need some kind of dissasembler to go back from the bytecode into java.

          • 2. Re: How can get the initial member field value?

            Thanks a lot for your quick reply.

            Can this possibly be done via javassist high level api, such as api form CtField? I also saw there is a class FieldInfo in javassist, does this contain the initial value for class members? if yes how to get it?

             

            Or not sure if you could provide just a little java sample code so I can start with...

             

            Really thanks a lot.