package samples.interceptor;
import java.lang.reflect.Field;
import alt.jiapi.InstrumentationContext;
import alt.jiapi.InstrumentationDescriptor;
import alt.jiapi.reflect.Loader;
import alt.jiapi.reflect.JiapiClass;
import alt.jiapi.util.Bootstrapper;
import alt.jiapi.util.InstrumentingClassLoader;
import alt.jiapi.interceptor.*;
/**
* Sample2 demonstrates how to intercept field accesses
* made.
* One is free to modify method call parameters / return value at will, as
* long as their type matches methods signature.
*/
public class Sample2 implements AccessAdvisor, FieldHandler {
public static void main(String args[]) throws Exception {
new Sample2();
}
public Sample2() throws Exception {
// Configure:
InstrumentationContext ctx = new InstrumentationContext();
InstrumentationDescriptor id = new InstrumentationDescriptor();
id.addInclusionRule("samples.*");
ctx.addInstrumentationDescriptor(id);
// Associate interceptor with descriptor
// Set resolution to 'samples*', which means that interceptor applies
// its work only on fields which start with 'samples'
// FieldInterceptor uses AccessAdvisor
FieldInterceptor fi = new FieldInterceptor(id, "samples*",this);
// FieldInterceptor2 uses reflection/FieldHandler. This is obsolete.
// Performance is roughly 100 times slower
//FieldInterceptor2 fi2 = new FieldInterceptor2(id, "samples*Bar*", this);
// Launch ITest
Bootstrapper.launch("samples.Foo", null, ctx,
InstrumentingClassLoader.createClassLoader(ctx));
}
/**
* FieldAdvisor
*
* @param o target instance. If this is null, target Method is
* static
* @param m Method, that this handler is supposed to invoke
* @param args Arguments, that are suitable to be passed to
* reflective method.
*/
public Object get(Object o, String name, Object value) {
System.out.println(" Getting field " + name + ": ");
if (value instanceof String) {
value = ((String)value).toUpperCase();
}
else if (value instanceof Integer) {
value = new Integer(100);
}
return value;
}
/**
* FieldAdvisor interface
*
* @param o target instance. If this is null, target Method is
* static
* @param m Method, that this handler is supposed to invoke
* @param args Arguments, that are suitable to be passed to
* reflective method.
*/
public Object set(Object o, String name, Object value) {
System.out.println(" Setting field " + name + ": " + value);
return value;
}
// FieldHandler interface -- Used with FieldInterceptor2
public void setField(Object target, Field field, Object value) throws Exception {
//System.out.println("Setting field");
field.set(target, value);
}
public Object getField(Object target, Field field) throws Exception {
System.out.println("getting");
return field.get(target);
}
}