里我不是记录操作,而是选择实际修改存 储在所选字段中的 String 值。在 FieldSetEditor 中,我实现了匹配字段访问的方法签名 。在这个方法中,我只检查两样东西:字段名是否是我所查找的,操作是否是一个存储过程 。找到匹配后,就用使用实际的 TranslateEditor 应用程序类中 reverse() 方法调用的结 果来替换原来的存储。 reverse() 方法就是将原来字符串中的字母顺序颠倒并输出一条消息 表明它已经使用过了。
清单 5. 颠倒字符串集
public class TranslateEditor
{
public static void main(String[] args) {
if (args.length >= 3) {
try {
// set up class loader with translator
EditorTranslator xlat =
new EditorTranslator(args[0], new FieldSetEditor(args [1]));
ClassPool pool = ClassPool.getDefault(xlat);
Loader loader = new Loader(pool);
// invoke the "main" method of the application class
String[] pargs = new String[args.length-3];
System.arraycopy(args, 3, pargs, 0, pargs.length);
loader.run(args[2], pargs);
} catch (Throwable ex) {
ex.printStackTrace();
}
} else {
System.out.println("Usage: TranslateEditor clas-name " +
"field-name main-class args...");
}
}
public static String reverse(String value) {
int length = value.length();
StringBuffer buff = new StringBuffer(length);
for (int i = length-1; i >= 0; i--) {
buff.append(value.charAt(i));
}
System.out.println("TranslateEditor.reverse returning " + buff);
return buff.toString();
}
public static class EditorTranslator implements Translator
{
private String m_className;
private ExprEditor m_editor;
private EditorTranslator(String cname, ExprEditor editor) {
m_className = cname;
m_editor = editor;
}
public void start(ClassPool pool) {}
public void onWrite(ClassPool pool, String cname)
throws NotFoundException, CannotCompileException {
if (cname.equals(m_className)) {
CtClass clas = pool.get(cname);
clas.instrument(m_editor);
}
}
}
public static class FieldSetEditor extends ExprEditor
{
private String m_fieldName;
private FieldSetEditor(String fname) {
m_fieldName = fname;
}
public void edit(FieldAccess arg) throws CannotCompileException {
if (arg.getFieldName().equals(m_fieldName) && arg.isWriter()) {
StringBuffer code = new StringBuffer();
code.append("$0.");
code.app
|