[jboss-user] [Javassist user questions] - Accessing static variables...
DonnieDarko1985
do-not-reply at jboss.com
Sat May 17 06:37:19 EDT 2008
I have the following classes:
public class A {
public static int n =10;
}
---------------------------------
public class B {
public int x;
public B(int n){
this.x =n;
}
public int getx (){
return this.x;
}
public static void main(String args[]){
B b= new B(10);
b.getx();
}
}
-------------------------------------------------------------
Now I am using a Translator to modify the methods in B:
----------------------------------------------------------------
import javassist.*;
public class ChangeClass{
public static void main(String[] args) {
if (args.length >= 2) {
try {
// set up class loader with translator
Translator xlat = new SimpleTranslator(args[0]);
ClassPool pool = ClassPool.getDefault();
Loader loader = new Loader();
loader.addTranslator(pool, xlat);
// invoke "main" method of target class
String[] pargs = new String[args.length-2];
System.arraycopy(args, 2, pargs, 0, pargs.length);
loader.run(args[1], pargs);
System.out.println(A.n);
} catch (Throwable ex) {
ex.printStackTrace();
}
} else {
System.out.println("Usage: TranslateTiming" +
" class-name method-mname main-class args...");
}
}
public static class SimpleTranslator implements Translator
{
private String m_className;
public SimpleTranslator(String cname) {
m_className = cname;
}
public void start(ClassPool pool) {}
public void onLoad(ClassPool pool, String cname)
throws NotFoundException, CannotCompileException {
System.out.println(cname + " "+ m_className);
if (cname.equals(m_className)) {
CtClass newclas = pool.get(cname);
CtMethod [] origMethods = newclas.getDeclaredMethods();
CtMethod currMet;
for (int i = 0; i < origMethods.length-2; i++) {
currMet=(CtMethod)origMethods;
currMet.setBody("{A.n=15;return this."+currMet.getName()+"($$);}");
}
}
}
}
}
--------------------------------------------------------------------------
Now in the bold section....I m setting the static variable(n) of A as 15.
But the output...I get is still 10.
------------------------------------------------------------------------------
Can someone please help me with this?
View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4151585#4151585
Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4151585
More information about the jboss-user
mailing list