xref: /aosp_15_r20/external/javassist/sample/duplicate/Main.java (revision f1fbf3c2ab775ce834e0af96b7a85bdc7a0eac65)
1*f1fbf3c2SXin Li package sample.duplicate;
2*f1fbf3c2SXin Li 
3*f1fbf3c2SXin Li /*
4*f1fbf3c2SXin Li   Runtime metaobject (JDK 1.2 or later only).
5*f1fbf3c2SXin Li 
6*f1fbf3c2SXin Li   With the javassist.tools.reflect package, the users can attach a metaobject
7*f1fbf3c2SXin Li   to an object.  The metaobject can control the behavior of the object.
8*f1fbf3c2SXin Li   For example, you can implement fault tolerancy with this ability.  One
9*f1fbf3c2SXin Li   of the implementation techniques of fault tolernacy is to make a copy
10*f1fbf3c2SXin Li   of every object containing important data and maintain it as a backup.
11*f1fbf3c2SXin Li   If the machine running the object becomes down, the backup object on a
12*f1fbf3c2SXin Li   different machine is used to continue the execution.
13*f1fbf3c2SXin Li 
14*f1fbf3c2SXin Li   To make the copy of the object a real backup, all the method calls to
15*f1fbf3c2SXin Li   the object must be also sent to that copy.  The metaobject is needed
16*f1fbf3c2SXin Li   for this duplication of the method calls.  It traps every method call
17*f1fbf3c2SXin Li   and invoke the same method on the copy of the object so that the
18*f1fbf3c2SXin Li   internal state of the copy is kept equivalent to that of the original
19*f1fbf3c2SXin Li   object.
20*f1fbf3c2SXin Li 
21*f1fbf3c2SXin Li   First, run sample.duplicate.Viewer without a metaobject.
22*f1fbf3c2SXin Li 
23*f1fbf3c2SXin Li   % java sample.duplicate.Viewer
24*f1fbf3c2SXin Li 
25*f1fbf3c2SXin Li   This program shows a ball in a window.
26*f1fbf3c2SXin Li 
27*f1fbf3c2SXin Li   Then, run the same program with a metaobject, which is an instance
28*f1fbf3c2SXin Li   of sample.duplicate.DuplicatedObject.
29*f1fbf3c2SXin Li 
30*f1fbf3c2SXin Li   % java sample.duplicate.Main
31*f1fbf3c2SXin Li 
32*f1fbf3c2SXin Li   You would see two balls in a window.  This is because
33*f1fbf3c2SXin Li   sample.duplicate.Viewer is loaded by javassist.tools.reflect.Loader so that
34*f1fbf3c2SXin Li   a metaobject would be attached.
35*f1fbf3c2SXin Li */
36*f1fbf3c2SXin Li public class Main {
main(String[] args)37*f1fbf3c2SXin Li     public static void main(String[] args) throws Throwable {
38*f1fbf3c2SXin Li 	javassist.tools.reflect.Loader cl = new javassist.tools.reflect.Loader();
39*f1fbf3c2SXin Li 	cl.makeReflective("sample.duplicate.Ball",
40*f1fbf3c2SXin Li 			  "sample.duplicate.DuplicatedObject",
41*f1fbf3c2SXin Li 			  "javassist.tools.reflect.ClassMetaobject");
42*f1fbf3c2SXin Li 	cl.run("sample.duplicate.Viewer", args);
43*f1fbf3c2SXin Li     }
44*f1fbf3c2SXin Li }
45