I am trying to serialize an invocation handler to a file. I am only trying to serialize the following part as it is the only part of the program that will change:
public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
System.out.println("BEFORE");
method.invoke(original, args);
System.out.println("AFTER");
//System.out.println(method);
return null;
}
I get the following error
run:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
at jdkproxydemo.JdkProxyDemo.main(JdkProxyDemo.java:69)
C:\Users\ACK\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
Here is the full code:
public class JdkProxyDemo {
interface If {
int originalMethod(String s);
}
static class Original implements If {
public int originalMethod(String s) {
System.out.println(s);
return 0;
}
}
public static class Handler implements InvocationHandler, Serializable {
private final If original;
public Handler(If original) {
this.original = original;
}
public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
System.out.println("BEFORE");
method.invoke(original, args);
System.out.println("AFTER");
//System.out.println(method);
return null;
}
}
public static void main(String[] args) throws FileNotFoundException, IOException{
/// OutputStream file = null;
Original original = new Original();
Handler handler = new Handler(original);
If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),new Class[] { If.class },handler);
OutputStream file = new FileOutputStream("quarks.ser");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject(handler.invoke(f,handler.original,"a"));
output.close();
}
}
What is the best way to achieve this result, serializing a proxy object?
Your code is currently trying to serialize
private final If originalbecause it's part ofHandler. However theIfinterface does not extendSerializable, so you cannot serializeHandler. You should either change toOr if that is not possible, you should use a different serialization method than Java serialization.