01: /*
02: * Javassist, a Java-bytecode translator toolkit.
03: * Copyright (C) 1999-2006 Shigeru Chiba. All Rights Reserved.
04: *
05: * The contents of this file are subject to the Mozilla Public License Version
06: * 1.1 (the "License"); you may not use this file except in compliance with
07: * the License. Alternatively, the contents of this file may be used under
08: * the terms of the GNU Lesser General Public License Version 2.1 or later.
09: *
10: * Software distributed under the License is distributed on an "AS IS" basis,
11: * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12: * for the specific language governing rights and limitations under the
13: * License.
14: */
15:
16: package javassist.convert;
17:
18: import javassist.bytecode.*;
19: import javassist.CtClass;
20: import javassist.CtField;
21: import javassist.Modifier;
22:
23: final public class TransformFieldAccess extends Transformer {
24: private String newClassname, newFieldname;
25: private String fieldname;
26: private CtClass fieldClass;
27: private boolean isPrivate;
28:
29: /* cache */
30: private int newIndex;
31: private ConstPool constPool;
32:
33: public TransformFieldAccess(Transformer next, CtField field,
34: String newClassname, String newFieldname) {
35: super (next);
36: this .fieldClass = field.getDeclaringClass();
37: this .fieldname = field.getName();
38: this .isPrivate = Modifier.isPrivate(field.getModifiers());
39: this .newClassname = newClassname;
40: this .newFieldname = newFieldname;
41: this .constPool = null;
42: }
43:
44: public void initialize(ConstPool cp, CodeAttribute attr) {
45: if (constPool != cp)
46: newIndex = 0;
47: }
48:
49: /**
50: * Modify GETFIELD, GETSTATIC, PUTFIELD, and PUTSTATIC so that
51: * a different field is accessed. The new field must be declared
52: * in a superclass of the class in which the original field is
53: * declared.
54: */
55: public int transform(CtClass clazz, int pos, CodeIterator iterator,
56: ConstPool cp) {
57: int c = iterator.byteAt(pos);
58: if (c == GETFIELD || c == GETSTATIC || c == PUTFIELD
59: || c == PUTSTATIC) {
60: int index = iterator.u16bitAt(pos + 1);
61: String typedesc = TransformReadField.isField(clazz
62: .getClassPool(), cp, fieldClass, fieldname,
63: isPrivate, index);
64: if (typedesc != null) {
65: if (newIndex == 0) {
66: int nt = cp.addNameAndTypeInfo(newFieldname,
67: typedesc);
68: newIndex = cp.addFieldrefInfo(cp
69: .addClassInfo(newClassname), nt);
70: constPool = cp;
71: }
72:
73: iterator.write16bit(newIndex, pos + 1);
74: }
75: }
76:
77: return pos;
78: }
79: }
|