### Example: Adding a Default Constructor Source: https://www.javassist.org/html/javassist/bytecode/MethodInfo.html Example code demonstrating how to add a default constructor to a class using MethodInfo, Bytecode, and ClassFile. ```APIDOC ## Example: Adding a Default Constructor ```java ClassFile cf = ...; // Assume cf is an existing ClassFile object ConstPool cp = cf.getConstPool(); Bytecode code = new Bytecode(cp); code.addAload(0); code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V"); code.addReturn(null); code.setMaxLocals(1); MethodInfo minfo = new MethodInfo(cp, MethodInfo.nameInit, "()V"); minfo.setCodeAttribute(code.toCodeAttribute()); cf.addMethod(minfo); ``` ``` -------------------------------- ### Bytecode Sequence Example Source: https://www.javassist.org/html/javassist/bytecode/Bytecode.html This represents the generated bytecode sequence for the previous example, consisting of iconst_3 and ireturn. ```assembly iconst_3 ireturn ``` -------------------------------- ### Configure ProxyFactory writeReplace Method Installation Source: https://www.javassist.org/html/javassist/util/proxy/ProxyFactory.html Configures whether this factory should install a `writeReplace` method in created classes for serialization. ```java public void setUseWriteReplace​(boolean useWriteReplace) ``` -------------------------------- ### Viewer Main Method Source: https://www.javassist.org/html/javassist/tools/web/Viewer.html Entry point for starting the Viewer application. ```java public static void main​(java.lang.String[] args) throws java.lang.Throwable ``` -------------------------------- ### Loader Usage Example with Translator Source: https://www.javassist.org/html/javassist/Loader.html Example demonstrating how to use the Javassist Loader with a Translator to modify class files during runtime. ```APIDOC ## Using Javassist Loader with a Translator ### Description This example shows how to set up a Javassist `Loader` with a custom `Translator` to modify classes before they are loaded. The `run()` method is then used to execute the main application class. ### Example Code ```java import javassist.*; public class Main { public static void main(String[] args) throws Throwable { MyTranslator myTrans = new MyTranslator(); // Assuming MyTranslator implements javassist.Translator ClassPool cp = ClassPool.getDefault(); Loader cl = new Loader(cp); cl.addTranslator(cp, myTrans); cl.run("MyApp", args); // "MyApp" is the main class to execute } } ``` ### Execution To run this program, compile and execute the `Main` class: ```bash % java Main _arg1_ _arg2_... ``` This will execute `MyApp` with modifications applied by `MyTranslator` at load time. ``` -------------------------------- ### Viewer Usage Example Source: https://www.javassist.org/html/javassist/tools/web/Viewer.html Demonstrates how to use the Viewer class to run a remote program. ```APIDOC ## Usage Example To run a program, use the following command: ```bash java javassist.tools.web.Viewer _host port_ Main arg1, ... ``` This command calls `Main.main()` with `arg1,...`. All classes, including `Main`, are fetched from a server `http://_host_:_port_`. Only the class file for `Viewer` must exist on the client side. Example of accessing Viewer methods from a loaded program: ```java Viewer v = (Viewer)this.getClass().getClassLoader(); String port = v.getPort(); ``` ``` -------------------------------- ### HotSwapAgent Entry Point Source: https://www.javassist.org/html/index-all.html The entry point for the HotSwapAgent when started after the JVM. ```APIDOC ## agentmain(String, Instrumentation) ### Description The entry point invoked when this agent is started after the JVM starts. ### Method Static method ### Endpoint N/A (Static method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### ClassFileWriter.MethodWriter.begin Source: https://www.javassist.org/html/javassist/bytecode/class-use/ClassFileWriter.AttributeWriter.html Starts the definition of a new method using an AttributeWriter. ```APIDOC ## MethodWriter.begin ### Description Starts adding a new method to the class. ### Parameters #### Request Body - **accessFlags** (int) - Required - The access flags for the method. - **name** (int/String) - Required - The name of the method. - **descriptor** (int/String) - Required - The method descriptor. - **exceptions** (int[]/String[]) - Required - The exceptions thrown by the method. - **aw** (ClassFileWriter.AttributeWriter) - Required - The attribute writer for the method. ``` -------------------------------- ### Get Parameter List Descriptor Source: https://www.javassist.org/html/javassist/bytecode/Descriptor.html Creates a descriptor string representing a list of parameter types. For example, `(II)` for two integers. ```java public static java.lang.String ofParameters​(CtClass[] paramTypes) ``` -------------------------------- ### Implement AttributeWriter to Write Synthetic Attribute Source: https://www.javassist.org/html/javassist/bytecode/ClassFileWriter.AttributeWriter.html Example of implementing the AttributeWriter interface to write a synthetic attribute. Requires a ConstPoolWriter to get the tag for the attribute name. ```java ConstPoolWriter cpw = ...; final int tag = cpw.addUtf8Info("Synthetic"); AttributeWriter aw = new AttributeWriter() { public int size() { return 1; } public void write(DataOutputStream out) throws java.io.IOException { out.writeShort(tag); out.writeInt(0); } }; ``` -------------------------------- ### Webserver Method: main Source: https://www.javassist.org/html/javassist/tools/web/Webserver.html Starts a web server. The port number is provided as the first argument. This method can throw an IOException. ```java public static void main(java.lang.String[] args) throws java.io.IOException ``` -------------------------------- ### Execute Dump Tool Source: https://www.javassist.org/html/javassist/tools/Dump.html Example of how to run the Dump tool from the command line to inspect a class file. ```bash % java javassist.tools.Dump foo.class ``` -------------------------------- ### Alternative Startup Program using Reflection Class Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html This alternative program uses the Reflection class and a Javassist Loader with a specific ClassPool to achieve similar reflective capabilities. ```java public class Main3 { public static void main(String[] args) throws Throwable { Reflection reflection = new Reflection(); javassist.Loader cl = new javassist.Loader(ClassPool.getDefault(reflection)); reflection.makeReflective("Person", "MyMetaobject", "javassist.tools.reflect.ClassMetaobject"); cl.run("MyApp", args); } } ``` -------------------------------- ### Startup Program for Reflective Classes (Method 1) Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html Use this startup program when the Main class is loaded by javassist.tools.reflect.Loader, ensuring it shares the same security domain. ```java public class Main { public static void main(String[] args) throws Throwable { javassist.tools.reflect.Loader cl = (javassist.tools.reflect.Loader)Main.class.getClassLoader(); cl.makeReflective("Person", "MyMetaobject", "javassist.tools.reflect.ClassMetaobject"); cl.run("MyApp", args); } } ``` -------------------------------- ### Get Next Instruction Index Source: https://www.javassist.org/html/javassist/bytecode/CodeIterator.html Returns the index of the next instruction, not the operand. The index is into the byte array obtained from get().getCode(). Throws BadBytecode if there are no more instructions. ```java public int next() throws BadBytecode ``` -------------------------------- ### run Method Source: https://www.javassist.org/html/javassist/tools/web/Webserver.html Begins the HTTP service. ```APIDOC ## run ### Description Begins the HTTP service. ### Method public ### Endpoint / ### Response #### Success Response (200) - **status** (string) - Indicates the service has started. #### Response Example ```json { "status": "HTTP service started" } ``` ``` -------------------------------- ### Loader Usage Example for Class Modification Source: https://www.javassist.org/html/javassist/Loader.html Example demonstrating how to use the Javassist Loader to modify a specific class (e.g., changing its superclass) without a separate Translator. ```APIDOC ## Using Javassist Loader for Direct Class Modification ### Description This example illustrates how to directly modify a specific class using Javassist `CtClass` and then load it using the `Loader`. This is useful when only a few classes require modification. ### Example Code ```java import javassist.*; // Assuming MyApp is the main class to execute and test.Rectangle and test.Point exist // ClassPool cp = ClassPool.getDefault(); // Loader cl = new Loader(cp); // CtClass ct = cp.get("test.Rectangle"); // ct.setSuperclass(cp.get("test.Point")); // cl.run("MyApp", args); ``` ### Explanation In this scenario, `test.Rectangle`'s superclass is changed to `test.Point` before `MyApp` is executed. This modification is applied directly to the `CtClass` object obtained from the `ClassPool`. ``` -------------------------------- ### Creating a Proxy Class and Instance Source: https://www.javassist.org/html/javassist/util/proxy/ProxyFactory.html Demonstrates how to use ProxyFactory to create a proxy class, instantiate it, and set a method handler. ```APIDOC ## Creating and Using Proxies ### Example Usage ```java ProxyFactory f = new ProxyFactory(); f.setSuperclass(Foo.class); f.setFilter(new MethodFilter() { public boolean isHandled(Method m) { // ignore finalize() return !m.getName().equals("finalize"); } }); Class c = f.createClass(); MethodHandler mi = new MethodHandler() { public Object invoke(Object self, Method m, Method proceed, Object[] args) throws Throwable { System.out.println("Name: " + m.getName()); return proceed.invoke(self, args); // execute the original method. } }; Foo foo = (Foo)c.newInstance(); ((Proxy)foo).setHandler(mi); // Method call on the proxy instance foo.bar(); ``` ### Instantiating with MethodHandler Alternatively, you can use the `create` helper method to generate, instantiate, and set the method handler in one step: ```java Foo foo = (Foo)f.create(new Class[0], new Object[0], mi); ``` ### Setting Method Handler at Runtime To change the method handler of an existing proxy instance: ```java MethodHandler mi = ... ; // alternative handler ((Proxy)foo).setHandler(mi); ``` ``` -------------------------------- ### Startup Program for Reflective Classes (Method 2) Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html Use this startup program when the Main2 class is not loaded by javassist.tools.reflect.Loader, placing it in a different security domain. ```java public class Main2 { public static void main(String[] args) throws Throwable { javassist.tools.reflect.Loader cl = new javassist.tools.reflect.Loader(); cl.makeReflective("Person", "MyMetaobject", "javassist.tools.reflect.ClassMetaobject"); cl.run("MyApp", args); } } ``` -------------------------------- ### Check if ProxyFactory Installs writeReplace Method Source: https://www.javassist.org/html/javassist/util/proxy/ProxyFactory.html Returns `true` if this factory installs a `writeReplace` method in created classes, enabling conventional serialization. Returns `false` otherwise. ```java public boolean isUseWriteReplace() ``` -------------------------------- ### Custom ClassMap Implementation Example Source: https://www.javassist.org/html/javassist/ClassMap.html Define a subclass of ClassMap to implement a custom mapping algorithm. This example demonstrates mapping 'java.' prefixed class names to 'java2.' prefixed names. ```java class MyClassMap extends ClassMap { public Object get(Object jvmClassName) { String name = toJavaName((String)jvmClassName); if (name.startsWith("java.")) return toJvmName("java2." + name.substring(5)); else return super.get(jvmClassName); } } ``` -------------------------------- ### javassist.tools.web.Webserver.run() Source: https://www.javassist.org/html/index-all.html Begins the HTTP service for the Webserver component. ```APIDOC ## Method run() ### Description Begins the HTTP service. ### Method void ### Endpoint javassist.tools.web.Webserver.run() ``` -------------------------------- ### Add exception table entry with CtClass Source: https://www.javassist.org/html/javassist/bytecode/Bytecode.html Adds a new entry to the exception table, specifying the start and end of the code range, the handler's starting PC, and the type of exception caught as a CtClass object. ```java public void addExceptionHandler(int start, int end, int handler, CtClass type) ``` -------------------------------- ### Create Proxy Instance with Helper Method Source: https://www.javassist.org/html/javassist/util/proxy/ProxyFactory.html The `create` helper method simplifies the process of generating a proxy class, instantiating it, and setting its method handler in a single call. Use this for a more concise way to obtain a configured proxy instance. ```java Foo foo = (Foo)f.create(new Class[0], new Object[0], mi); ``` -------------------------------- ### Webserver Initialization and Control Source: https://www.javassist.org/html/javassist/tools/web/Webserver.html Methods for initializing the web server, managing class pools, and handling lifecycle events. ```APIDOC ## Webserver Initialization ### Description Constructs a new instance of the Webserver to serve files and instrument classes. ### Parameters #### Path Parameters - **port** (int/String) - Required - The port number on which the server will listen. ## addTranslator ### Description Adds a translator to the server, which is invoked whenever a client requests a class file. ### Parameters - **cp** (ClassPool) - Required - The ClassPool object for obtaining class files. - **t** (Translator) - Required - The translator instance to process class files. ## end ### Description Closes the server socket and terminates the service. ### Method void end() ## setClassPool ### Description Configures the server to use a specific ClassPool object for class file retrieval. ### Parameters - **loader** (ClassPool) - Required - The ClassPool instance to be used. ``` -------------------------------- ### Add exception table entry with type index Source: https://www.javassist.org/html/javassist/bytecode/Bytecode.html Adds a new entry to the exception table, specifying the start and end of the code range, the handler's starting PC, and the type of exception caught as a ConstPool index. ```java public void addExceptionHandler(int start, int end, int handler, int type) ``` -------------------------------- ### Example: Retrieving an Annotation Source: https://www.javassist.org/html/javassist/bytecode/AnnotationsAttribute.html Demonstrates how to retrieve a specific annotation (e.g., 'Author') from a MethodInfo object. ```APIDOC ## Example: Retrieving an Annotation This code snippet retrieves an annotation of the type `Author` from the `MethodInfo` object specified by `minfo`. Then, it prints the value of `name` in `Author`. ```java import javassist.bytecode.annotation.Annotation; import javassist.bytecode.MethodInfo; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.annotation.StringMemberValue; // Assume 'm' is a CtMethod and 'minfo' is its MethodInfo object // MethodInfo minfo = m.getMethodInfo(); AnnotationsAttribute attr = (AnnotationsAttribute) minfo.getAttribute(AnnotationsAttribute.invisibleTag); Annotation an = attr.getAnnotation("Author"); String s = ((StringMemberValue)an.getMemberValue("name")).getValue(); System.out.println("@Author(name=" + s + ")"); ``` **Note:** If the annotation is runtime visible, use `AnnotationsAttribute.visibleTag` instead of `AnnotationsAttribute.invisibleTag`. ``` -------------------------------- ### GET /getSuperclass Source: https://www.javassist.org/html/javassist/CtClass.html Obtains the superclass of the class. ```APIDOC ## GET /getSuperclass ### Description Obtains the class object representing the superclass of the class. Returns null if the class is java.lang.Object. ### Method GET ### Response #### Success Response (200) - **return** (CtClass) - The superclass object. ### Errors - **NotFoundException** - Thrown if the superclass cannot be found. ``` -------------------------------- ### Add exception table entry with class name Source: https://www.javassist.org/html/javassist/bytecode/Bytecode.html Adds a new entry to the exception table, specifying the start and end of the code range, the handler's starting PC, and the type of exception caught as a class name string. ```java public void addExceptionHandler(int start, int end, int handler, java.lang.String type) ``` -------------------------------- ### Webserver Class and Constructors Source: https://www.javassist.org/html/index-all.html Information about the Webserver class and its constructors for running sample programs. ```APIDOC ## Webserver - Class in javassist.tools.web ### Description A web server for running sample programs. ## Webserver(int) - Constructor for class javassist.tools.web.Webserver ### Description Constructs a web server. ## Webserver(String) - Constructor for class javassist.tools.web.Webserver ### Description Constructs a web server. ``` -------------------------------- ### Example of using ExprEditor to inspect method calls Source: https://www.javassist.org/html/javassist/expr/ExprEditor.html This example demonstrates how to use ExprEditor to inspect all method calls within a CtMethod. It prints the names and line numbers of methods declared in the 'Point' class without modifying the method body. ```java CtMethod cm = ...; cm.instrument(new ExprEditor() { public void edit(MethodCall m) throws CannotCompileException { if (m.getClassName().equals("Point")) { System.out.println(m.getMethodName() + " line: " + m.getLineNumber()); } }); ``` -------------------------------- ### Initialize ClassPool with System Path Option Source: https://www.javassist.org/html/javassist/ClassPool.html Creates a root class pool, optionally appending the system search path if the useDefaultPath parameter is true. ```java public ClassPool(boolean useDefaultPath) ``` -------------------------------- ### Method: main Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html Static entry point to load a class and execute its main method using the reflective loader. ```APIDOC ## Method: main ### Description Loads a class with an instance of Loader and calls the main() method in that class. ### Parameters - **args** (String[]) - Command line parameters. args[0] is the class name to be loaded, args[1..n] are parameters passed to the target main(). ### Throws - java.lang.Throwable ``` -------------------------------- ### GET /lookupCflow Source: https://www.javassist.org/html/index-all.html Looks up a cflow definition in the ClassPool. ```APIDOC ## GET /lookupCflow ### Description Undocumented method to lookup cflow. ### Method GET ### Endpoint /lookupCflow ### Parameters #### Query Parameters - **name** (String) - Required - The name of the cflow to lookup. ``` -------------------------------- ### Sample Class - Constructor Source: https://www.javassist.org/html/javassist/tools/reflect/Sample.html Details the constructor for the Sample class. ```APIDOC ## Constructor: Sample ### Description Initializes a new instance of the Sample class. ### Signature ```java public Sample() ``` ``` -------------------------------- ### GET /getInterfaces Source: https://www.javassist.org/html/javassist/CtClass.html Obtains the interfaces implemented by the class. ```APIDOC ## GET /getInterfaces ### Description Obtains the class objects representing the interfaces implemented by the class. ### Method GET ### Response #### Success Response (200) - **return** (CtClass[]) - Array of implemented interfaces. ### Errors - **NotFoundException** - Thrown if interfaces cannot be found. ``` -------------------------------- ### Begin Method Definition Source: https://www.javassist.org/html/javassist/bytecode/ClassFileWriter.MethodWriter.html Starts the definition of a new method using either string-based or constant pool index-based parameters. ```java public void begin​(int accessFlags, java.lang.String name, java.lang.String descriptor, java.lang.String[] exceptions, ClassFileWriter.AttributeWriter aw) ``` ```java public void begin​(int accessFlags, int name, int descriptor, int[] exceptions, ClassFileWriter.AttributeWriter aw) ``` -------------------------------- ### GET /getName Source: https://www.javassist.org/html/javassist/CtClass.html Obtains the fully-qualified name of the class. ```APIDOC ## GET /getName ### Description Obtains the fully-qualified name of the class. ### Method GET ### Response #### Success Response (200) - **name** (String) - The fully-qualified class name. ``` -------------------------------- ### Obtain a Control Flow Graph Source: https://www.javassist.org/html/javassist/bytecode/analysis/ControlFlow.html Demonstrates how to initialize a ControlFlow instance from a CtMethod and retrieve its basic blocks. ```java CtMethod m = ... ControlFlow cf = new ControlFlow(m); Block[] blocks = cf.basicBlocks(); ``` -------------------------------- ### GET /isFrozen Source: https://www.javassist.org/html/javassist/CtClass.html Checks if the class is frozen and cannot be modified. ```APIDOC ## GET /isFrozen ### Description Returns true if the class has been loaded or written out and thus it cannot be modified any more. ### Method GET ### Response #### Success Response (200) - **frozen** (boolean) - True if the class is frozen. ``` -------------------------------- ### Run Viewer via Command Line Source: https://www.javassist.org/html/javassist/tools/web/Viewer.html Execute the Viewer application to load and run a main class from a remote server. ```bash % java javassist.tools.web.Viewer _host port_ Main arg1, ... ``` -------------------------------- ### GET /isModified Source: https://www.javassist.org/html/javassist/CtClass.html Checks if the class definition has been modified. ```APIDOC ## GET /isModified ### Description Returns true if the definition of the class has been modified. ### Method GET ### Response #### Success Response (200) - **modified** (boolean) - True if modified, false otherwise. ``` -------------------------------- ### Example: Creating a New AnnotationAttribute Source: https://www.javassist.org/html/javassist/bytecode/AnnotationsAttribute.html Shows how to create and add a new AnnotationAttribute to a ClassFile object. ```APIDOC ## Example: Creating a New AnnotationAttribute This snippet demonstrates how to record a new AnnotationAttribute object. ```java import javassist.bytecode.ClassFile; import javassist.bytecode.ConstPool; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.StringMemberValue; // Assume 'cf' is a ClassFile object // ClassFile cf = ... ; ConstPool cp = cf.getConstPool(); AnnotationsAttribute attr = new AnnotationsAttribute(cp, AnnotationsAttribute.visibleTag); Annotation a = new Annotation("Author", cp); a.addMemberValue("name", new StringMemberValue("Chiba", cp)); attr.setAnnotation(a); cf.addAttribute(attr); cf.setVersionToJava5(); // Necessary if compiled with JDK 1.4 or earlier ``` ``` -------------------------------- ### Running Reflective Application (Method 1) Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html Command to run the application using the Main class, which is loaded by javassist.tools.reflect.Loader. ```bash % java javassist.tools.reflect.Loader Main arg1, ... ``` -------------------------------- ### GET /getURL Source: https://www.javassist.org/html/javassist/CtClass.html Retrieves the URL of the class file. ```APIDOC ## GET /getURL ### Description Returns the uniform resource locator (URL) of the class file. ### Method GET ### Response #### Success Response (200) - **URL** (java.net.URL) - The URL of the class file. ### Errors - **NotFoundException** - Thrown if the URL cannot be found. ``` -------------------------------- ### Get Array Dimension Source: https://www.javassist.org/html/javassist/bytecode/SignatureAttribute.ArrayType.html Retrieves the dimension of the array. ```java public int getDimension() ``` -------------------------------- ### Run Compiler from Command Line Source: https://www.javassist.org/html/javassist/tools/reflect/Compiler.html Example usage of the Compiler class to modify class files with specific metaobject configurations. ```bash % java Compiler Dog -m MetaDog -c CMetaDog Cat -m MetaCat Cow ``` -------------------------------- ### Sample Class Methods Source: https://www.javassist.org/html/javassist/tools/rmi/Sample.html Details the instance and static methods of the Sample class. ```APIDOC ## forward(Object[] args, int identifier) ### Description Handles method invocation forwarding for instance methods. ### Method Instance Method ### Endpoint N/A ### Parameters - **args** (Object[]) - Arguments for the method call. - **identifier** (int) - Identifier for the method. ### Request Body None ### Response - **return value** (Object) - The result of the method invocation. ### Request Example ```java // Example usage within a proxy context Object result = sample.forward(methodArgs, methodIdentifier); ``` ## forwardStatic(Object[] args, int identifier) ### Description Handles method invocation forwarding for static methods. ### Method Static Method ### Endpoint N/A ### Parameters - **args** (Object[]) - Arguments for the method call. - **identifier** (int) - Identifier for the method. ### Request Body None ### Response - **return value** (Object) - The result of the method invocation. ### Throws - **RemoteException** - If a remote communication error occurs. ### Request Example ```java // Example usage within a proxy context for static methods Object result = Sample.forwardStatic(methodArgs, methodIdentifier); ``` ``` -------------------------------- ### Get number of parameters Source: https://www.javassist.org/html/javassist/bytecode/ParameterAnnotationsAttribute.html Returns the num_parameters value. ```java public int numParameters() ``` -------------------------------- ### Implement Singleton Pattern with createPoint Source: https://www.javassist.org/html/javassist/CodeConverter.html Example of a static method used to intercept instantiation and implement a singleton pattern. ```java public static Point createPoint(int x, int y) { if (aPoint == null) aPoint = new Point(x, y); return aPoint; } ``` -------------------------------- ### Get Code Bytes Source: https://www.javassist.org/html/javassist/bytecode/CodeAttribute.html Returns the code array. ```java public byte[] getCode() ``` -------------------------------- ### Get Max Locals Source: https://www.javassist.org/html/javassist/bytecode/CodeAttribute.html Returns the value of max_locals. ```java public int getMaxLocals() ``` -------------------------------- ### Get Max Stack Source: https://www.javassist.org/html/javassist/bytecode/CodeAttribute.html Returns the value of max_stack. ```java public int getMaxStack() ``` -------------------------------- ### Constructor Detail: MethodInfo Source: https://www.javassist.org/html/javassist/bytecode/MethodInfo.html Details for the `MethodInfo` constructor. ```APIDOC ## Constructor Detail: MethodInfo ### `public MethodInfo(ConstPool cp, java.lang.String methodname, java.lang.String desc)` Constructs a `method_info` structure. ``` -------------------------------- ### Main Method - Dump.main() Source: https://www.javassist.org/html/javassist/tools/Dump.html The `main` method is the entry point for the Dump tool, accepting command-line arguments to specify the class file to process. ```APIDOC ## Dump.main() ### Description This is the main method for the `javassist.tools.Dump` class. It serves as the entry point for executing the Dump tool from the command line. It processes the provided class file and outputs its structural information. ### Method `public static void main(java.lang.String[] args)` ### Endpoint N/A (This is a static method within the Dump class) ### Parameters #### Method Parameters - **`args`** (java.lang.String[]) - Required - An array of strings representing command-line arguments. `args[0]` is expected to be the path to the class file to be dumped. ### Throws - **`java.lang.Exception`** - This exception may be thrown if an error occurs during the processing of the class file. ### Request Example (This is a method signature, not a direct request example. See Dump Tool Usage for command-line execution.) ### Response #### Success Response - The method executes the Dump tool's functionality, printing class file details to standard output. #### Response Example (See Dump Tool Usage for example output.) ``` -------------------------------- ### CtClass getAccessorMaker() Source: https://www.javassist.org/html/index-all.html Undocumented method to get an accessor maker. ```APIDOC ## GET CtClass.getAccessorMaker() ### Description Undocumented method. ### Method GET ### Endpoint N/A (Method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Object** - The accessor maker. #### Response Example ```json { "accessorMakerType": "DefaultAccessorMaker" } ``` ``` -------------------------------- ### ProxyFactory.ClassLoaderProvider get(ProxyFactory) Source: https://www.javassist.org/html/index-all.html Returns a class loader from the ProxyFactory. ```APIDOC ## GET ProxyFactory.ClassLoaderProvider.get(ProxyFactory) ### Description Returns a class loader. ### Method GET ### Endpoint N/A (Method within an interface implementation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ClassLoader** - The ClassLoader instance. #### Response Example ```json { "classLoaderName": "sun.misc.Launcher$AppClassLoader" } ``` ``` -------------------------------- ### Field Detail: nameInit Source: https://www.javassist.org/html/javassist/bytecode/MethodInfo.html Details for the `nameInit` static String field. ```APIDOC ## Field Detail: nameInit ### `public static final java.lang.String nameInit` The name of constructors: ``. See Also: Constant Field Values ``` -------------------------------- ### Type get(CtClass) Source: https://www.javassist.org/html/index-all.html Obtains the Type for a given class. ```APIDOC ## GET Type.get(CtClass) ### Description Obtain the Type for a given class. ### Method GET ### Endpoint N/A (Static method within a class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Type** - The Type object representing the class. #### Response Example ```json { "typeName": "com.example.MyClass", "isPrimitive": false } ``` ``` -------------------------------- ### GET /javassist/URLClassPath/fetchClass Source: https://www.javassist.org/html/index-all.html Reads a class file from an HTTP server. ```APIDOC ## GET /javassist/URLClassPath/fetchClass ### Description Reads a class file on an http server. ### Method GET ### Parameters #### Query Parameters - **classname** (String) - Required - The name of the class to fetch. - **port** (int) - Required - The port number of the server. - **directory** (String) - Required - The directory path on the server. - **file** (String) - Required - The filename of the class file. ``` -------------------------------- ### Method Detail: accept(MemberValueVisitor visitor) Source: https://www.javassist.org/html/javassist/bytecode/annotation/LongMemberValue.html Details on how to accept a MemberValueVisitor. ```APIDOC #### accept ```java public void accept(MemberValueVisitor visitor) ``` Accepts a visitor. Specified by: `accept` in class `MemberValue` ``` -------------------------------- ### GET Metalevel._getMetaobject() Source: https://www.javassist.org/html/javassist/tools/reflect/class-use/Metaobject.html Retrieves the metaobject currently associated with the object. ```APIDOC ## GET Metalevel._getMetaobject() ### Description Obtains the metaobject associated with this object. ### Method GET ### Endpoint Metalevel._getMetaobject() ### Response #### Success Response (200) - **Metaobject** - The metaobject associated with the object. ``` -------------------------------- ### FieldInfo Constructor and Usage Example Source: https://www.javassist.org/html/javassist/bytecode/FieldInfo.html Demonstrates how to create and add a new public integer field named 'width' to a class file using FieldInfo. ```APIDOC ## FieldInfo Constructor and Usage ### Description This section shows how to construct a `FieldInfo` object and add it to a `ClassFile`. ### Method `FieldInfo(ConstPool cp, String fieldName, String desc)` ### Endpoint N/A (Class method) ### Parameters #### Constructor Parameters - **cp** (ConstPool) - The constant pool table. - **fieldName** (String) - The name of the field. - **desc** (String) - The descriptor of the field. ### Request Example ```java ClassFile cf = ...; // Assume cf is an initialized ClassFile object FieldInfo f = new FieldInfo(cf.getConstPool(), "width", "I"); f.setAccessFlags(AccessFlag.PUBLIC); cf.addField(f); ``` ### Response N/A (This is a code example demonstrating object creation and manipulation.) ``` -------------------------------- ### Sample Class Constructor Source: https://www.javassist.org/html/javassist/tools/rmi/Sample.html Details the default constructor for the Sample class. ```APIDOC ## Sample() ### Description Default constructor for the Sample class. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Body None ### Response None ### Constructor Example ```java Sample sample = new Sample(); ``` ``` -------------------------------- ### GET SignatureAttribute.ClassSignature.getParameters Source: https://www.javassist.org/html/javassist/bytecode/class-use/SignatureAttribute.TypeParameter.html Retrieves the type parameters from a class signature. ```APIDOC ## GET SignatureAttribute.ClassSignature.getParameters ### Description Returns the type parameters associated with the class signature. ### Method GET ### Response - **SignatureAttribute.TypeParameter[]** - An array of type parameters. ``` -------------------------------- ### GET /getDeclaringClass Source: https://www.javassist.org/html/javassist/CtClass.html Returns the enclosing class if this is a member class. ```APIDOC ## GET /getDeclaringClass ### Description If this class is a member class or interface of another class, then the class enclosing this class is returned. ### Method GET ### Response #### Success Response (200) - **return** (CtClass) - The enclosing class or null if top-level. ### Errors - **NotFoundException** - Thrown if the declaring class cannot be found. ``` -------------------------------- ### Proxy Class Example Source: https://www.javassist.org/html/javassist/tools/rmi/StubGenerator.html Illustrates the structure of a proxy class generated for a given class A. It includes methods for object import and retrieval of the object ID. ```java public class A implements Proxy, Serializable { private ObjectImporter importer; private int objectId; public int _getObjectId() { return objectId; } public A(ObjectImporter oi, int id) { importer = oi; objectId = id; } ... the same methods that the original class A declares ... } ``` -------------------------------- ### GET dominatorTree() Source: https://www.javassist.org/html/javassist/bytecode/analysis/ControlFlow.html Constructs and returns the dominator tree for the method. ```APIDOC ## GET dominatorTree() ### Description Constructs a dominator tree for the method. The first element of the returned array is the root of the tree. ### Response #### Success Response (200) - **ControlFlow.Node[]** - An array of tree nodes, or null if the method has no code. ``` -------------------------------- ### Create ClassPool with Default Path Source: https://www.javassist.org/html/javassist/ClassPool.html Initializes a root class pool and appends the system search path. This is used to create the default singleton ClassPool. ```java ClassPool cp = new ClassPool(); cp.appendSystemPath(); ``` -------------------------------- ### Get Component Type Source: https://www.javassist.org/html/javassist/bytecode/SignatureAttribute.ArrayType.html Retrieves the component type of the array. ```java public SignatureAttribute.Type getComponentType() ``` -------------------------------- ### Translator.start Source: https://www.javassist.org/html/javassist/Translator.html Initializes the translator when attached to a Loader. ```APIDOC ## void start(ClassPool pool) ### Description Is invoked by a Loader for initialization when the object is attached to the Loader object. This method can be used for getting (for caching) some CtClass objects that will be accessed in onLoad() in Translator. ### Parameters #### Request Body - **pool** (ClassPool) - Required - The ClassPool that this translator should use. ### Response #### Success Response (200) - **void** - Method completes successfully. #### Errors - **NotFoundException** - if a CtClass cannot be found. - **CannotCompileException** - if the initialization by this method fails. ``` -------------------------------- ### Get Exception Table Source: https://www.javassist.org/html/javassist/bytecode/CodeAttribute.html Returns the exception table array. ```java public ExceptionTable getExceptionTable() ``` -------------------------------- ### FactoryHelper Class Overview Source: https://www.javassist.org/html/javassist/util/proxy/FactoryHelper.html Provides a summary of the FactoryHelper class, its fields, constructors, and methods. ```APIDOC ## Class: javassist.util.proxy.FactoryHelper ### Description A helper class for implementing `ProxyFactory`. The users of `ProxyFactory` do not have to see this class. See Also: `ProxyFactory` ### Field Summary Fields Modifier and Type | Field | Description ---|---|--- `static int[]` | `dataSize` | The data size of primitive types. `static java.lang.Class[]` | `primitiveTypes` | `Class` objects representing primitive types. `static java.lang.String[]` | `unwarpMethods` | The names of methods for obtaining a primitive value from a wrapper object. `static java.lang.String[]` | `unwrapDesc` | The descriptors of the unwrapping methods contained in `unwrapMethods`. `static java.lang.String[]` | `wrapperDesc` | The descriptors of the constructors of wrapper classes. `static java.lang.String[]` | `wrapperTypes` | The fully-qualified names of wrapper classes for primitive types. ### Constructor Summary Constructors Constructor | Description ---|--- `FactoryHelper()` | ### Method Summary All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type | Method | Description ---|---|--- `static java.lang.Class` | `toClass(ClassFile cf, java.lang.Class neighbor, java.lang.ClassLoader loader, java.security.ProtectionDomain domain)` | Loads a class file by a given class loader. `static java.lang.Class` | `toClass(ClassFile cf, java.lang.ClassLoader loader)` | Deprecated. `static java.lang.Class` | `toClass(ClassFile cf, java.lang.ClassLoader loader, java.security.ProtectionDomain domain)` | Deprecated. `static java.lang.Class` | `toClass(ClassFile cf, java.lang.invoke.MethodHandles.Lookup lookup)` | Loads a class file by a given lookup. `static int` | `typeIndex(java.lang.Class type)` | Returns an index for accessing arrays in this class. `static void` | `writeFile(ClassFile cf, java.lang.String directoryName)` | Writes a class file. ### Methods inherited from class java.lang.Object `equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait` ``` -------------------------------- ### Get Code Length Source: https://www.javassist.org/html/javassist/bytecode/CodeAttribute.html Returns the length of the code array. ```java public int getCodeLength() ``` -------------------------------- ### Example of Class Mapping in CtMethod Source: https://www.javassist.org/html/javassist/CtMethod.html Demonstrates how class names are replaced in a method body using a ClassMap during copying. ```java public X at(int i) { return (X)super.elementAt(i); } ``` ```java public String at(int i) { return (String)super.elementAt(i); } ``` -------------------------------- ### Get Constant Value Index Source: https://www.javassist.org/html/javassist/bytecode/ConstantAttribute.html Retrieves the constantvalue_index from the attribute. ```java public int getConstantValue() ``` -------------------------------- ### Running Reflective Application (Method 2) Source: https://www.javassist.org/html/javassist/tools/reflect/Loader.html Command to run the application using Main2, which is not loaded by javassist.tools.reflect.Loader. ```bash % java Main2 arg1, ... ``` -------------------------------- ### GET /getParameterTypes Source: https://www.javassist.org/html/javassist/CtBehavior.html Obtains the parameter types of the method or constructor. ```APIDOC ## GET /getParameterTypes ### Description Obtains parameter types of this method/constructor. ### Method GET ### Endpoint /getParameterTypes ### Response #### Success Response (200) - **CtClass[]** - Array of parameter types. #### Errors - **NotFoundException** - Thrown if the parameter types cannot be found. ``` -------------------------------- ### make(String src, CtClass declaring, String delegateObj, String delegateMethod) Source: https://www.javassist.org/html/javassist/CtNewMethod.html Compiles the given source code and creates a method. If the source code includes $proceed(), then it is compiled into a method call on the specified object. ```APIDOC ## POST /ctnewmethod/make/delegate ### Description Compiles the given source code and creates a method. If the source code includes `$proceed()`, then it is compiled into a method call on the specified object. ### Method POST ### Endpoint `/ctnewmethod/make/delegate` ### Parameters #### Query Parameters - **src** (String) - Required - The source text. - **declaring** (CtClass) - Required - The class to which the created method is added. - **delegateObj** (String) - Required - The source text specifying the object that is called on by `$proceed()`. - **delegateMethod** (String) - Required - The name of the method that is called by `$proceed()`. ### Request Example ```json { "src": "public Object id(Object obj) { return $proceed(obj); }", "declaring": "com.example.MyClass", "delegateObj": "super", "delegateMethod": "id" } ``` ### Response #### Success Response (200) - **CtMethod** (CtMethod) - The newly created method. #### Response Example ```json { "methodName": "id", "returnType": "Object", "parameters": ["Object"] } ``` ### Throws - `CannotCompileException` ``` -------------------------------- ### Get Constructor Name Source: https://www.javassist.org/html/javassist/CtConstructor.html Obtains the simple name of this constructor. ```java java.lang.String getName() ``` -------------------------------- ### Static Method: make (Parameters and Body) Source: https://www.javassist.org/html/javassist/CtNewConstructor.html Creates a public constructor using specified parameters, exceptions, and a body string. ```APIDOC ## static CtConstructor make(CtClass[] parameters, CtClass[] exceptions, java.lang.String body, CtClass declaring) ### Description Creates a public constructor. ### Parameters - **parameters** (CtClass[]) - Required - A list of the parameter types. - **exceptions** (CtClass[]) - Required - A list of the exception types. - **body** (java.lang.String) - Required - The source text of the constructor body. It must be a block surrounded by {}. If it is null, the substituted constructor body does nothing except calling super(). - **declaring** (CtClass) - Required - The class to which the created method is added. ### Response - **CtConstructor** - The created constructor object. ``` -------------------------------- ### Webserver Class Source: https://www.javassist.org/html/javassist/tools/web/package-summary.html The Webserver class provides functionality for hosting sample programs. ```APIDOC ## Webserver ### Description A web server implementation designed for running sample programs within the Javassist project environment. ### Exceptions - **BadHttpRequest**: Thrown when the server receives an invalid HTTP request. ``` -------------------------------- ### Define an annotation type Source: https://www.javassist.org/html/javassist/bytecode/AnnotationDefaultAttribute.html Example of an annotation interface with default values. ```java @interface Author { String name() default "Shakespeare"; int age() default 99; } ``` -------------------------------- ### StackMap Entry Count Source: https://www.javassist.org/html/index-all.html Method to get the number of entries in a StackMap. ```APIDOC ## StackMap Entry Count ### Method - numOfEntries() Method in class javassist.bytecode.StackMap Returns `number_of_entries`. ``` -------------------------------- ### Method Summary Source: https://www.javassist.org/html/javassist/CtNewMethod.html Lists all static and concrete methods available in the CtNewMethod class. ```APIDOC ### Method Summary All Methods | Static Methods | Concrete Methods | Modifier and Type | Method | Description ---|---|---|---|---|--- | `static CtMethod` | | `abstractMethod​(CtClass returnType, java.lang.String mname, CtClass[] parameters, CtClass[] exceptions, CtClass declaring)` | Creates a public abstract method. | `static CtMethod` | | `copy​(CtMethod src, java.lang.String name, CtClass declaring, ClassMap map)` | Creates a copy of a method with a new name. | `static CtMethod` | | `copy​(CtMethod src, CtClass declaring, ClassMap map)` | Creates a copy of a method. | `static CtMethod` | | `delegator​(CtMethod delegate, CtClass declaring)` | Creates a method forwarding to a delegate in a super class. | `static CtMethod` | | `getter​(java.lang.String methodName, CtField field)` | Creates a public getter method. | `static CtMethod` | | `make​(int modifiers, CtClass returnType, java.lang.String mname, CtClass[] parameters, CtClass[] exceptions, java.lang.String body, CtClass declaring)` | Creates a method. | `static CtMethod` | | `make​(java.lang.String src, CtClass declaring)` | Compiles the given source code and creates a method. | `static CtMethod` | | `make​(java.lang.String src, CtClass declaring, java.lang.String delegateObj, java.lang.String delegateMethod)` | Compiles the given source code and creates a method. | `static CtMethod` | | `make​(CtClass returnType, java.lang.String mname, CtClass[] parameters, CtClass[] exceptions, java.lang.String body, CtClass declaring)` | Creates a public (non-static) method. | `static CtMethod` | | `setter​(java.lang.String methodName, CtField field)` | Creates a public setter method. | `static CtMethod` | | `wrapped​(CtClass returnType, java.lang.String mname, CtClass[] parameterTypes, CtClass[] exceptionTypes, CtMethod body, CtMethod.ConstParameter constParam, CtClass declaring)` | Creates a wrapped method. ``` -------------------------------- ### Descriptor Parameter Count Source: https://www.javassist.org/html/index-all.html Method to get the number of parameters in a descriptor. ```APIDOC ## Descriptor Parameter Count ### Method - numOfParameters(String descriptor) Static method in class javassist.bytecode.Descriptor Returns the number of the parameters included in the given descriptor. ``` -------------------------------- ### Sample Class Methods Source: https://www.javassist.org/html/index-all.html Methods for handling remote method invocation forwarding. ```APIDOC ## Sample Class Methods ### Description Methods related to sample implementations for remote method invocation. ### Methods - `forward(Object[], int)`: Forwards method calls. - `forwardStatic(Object[], int)`: Forwards static method calls. ### Endpoint N/A ### Parameters - `Object[]` - Array of objects. - `int` - An integer parameter. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Constructor Navigation Source: https://www.javassist.org/html/javassist/bytecode/CodeIterator.html Methods for skipping constructor initialization logic to locate specific invocation instructions. ```APIDOC ## skipConstructor ### Description Moves to the instruction for either super() or this(). ## skipSuperConstructor ### Description Moves to the instruction for super(). ## skipThisConstructor ### Description Moves to the instruction for this(). ``` -------------------------------- ### Get MethodHandler Source: https://www.javassist.org/html/javassist/util/proxy/ProxyObject.html Retrieves the current MethodHandler associated with the proxy object. ```java MethodHandler getHandler() ``` -------------------------------- ### Sample Class - Methods Source: https://www.javassist.org/html/javassist/tools/reflect/Sample.html Details the methods available in the Sample class for reflective operations. ```APIDOC ## Methods: Sample Class ### trap #### Description Handles general reflective calls. #### Signature ```java public Object trap(Object[] args, int identifier) throws Throwable ``` #### Parameters - **args** (Object[]) - Arguments for the reflective call. - **identifier** (int) - Identifier for the method being trapped. #### Throws - `java.lang.Throwable` ### trapStatic #### Description Handles reflective calls to static methods. #### Signature ```java public static Object trapStatic(Object[] args, int identifier) throws Throwable ``` #### Parameters - **args** (Object[]) - Arguments for the static reflective call. - **identifier** (int) - Identifier for the static method being trapped. #### Throws - `java.lang.Throwable` ### trapRead #### Description Handles reflective calls to read field values. #### Signature ```java public static Object trapRead(Object[] args, String name) ``` #### Parameters - **args** (Object[]) - Arguments for the reflective call. - **name** (String) - The name of the field to read. ### trapWrite #### Description Handles reflective calls to write field values. #### Signature ```java public static Object trapWrite(Object[] args, String name) ``` #### Parameters - **args** (Object[]) - Arguments for the reflective call. - **name** (String) - The name of the field to write. ``` -------------------------------- ### Get Port Number Source: https://www.javassist.org/html/javassist/tools/web/Viewer.html Retrieves the port number configured for the Viewer. ```java public int getPort() ``` -------------------------------- ### Example Usage of Analyzer Source: https://www.javassist.org/html/javassist/bytecode/analysis/Analyzer.html Demonstrates how to use the Analyzer to obtain frame states for a method and inspect local variables and stack types. ```java public void analyzeIt(CtClass clazz, MethodInfo method) { Analyzer analyzer = new Analyzer(); Frame[] frames = analyzer.analyze(clazz, method); frames[0].getLocal(0).getCtClass(); // returns clazz; frames[0].getLocal(1).getCtClass(); // returns java.lang.String frames[1].peek(); // returns Type.INTEGER frames[27].peek().getCtClass(); // returns java.lang.Number } ``` -------------------------------- ### Get Server Name Source: https://www.javassist.org/html/javassist/tools/web/Viewer.html Retrieves the server name configured for the Viewer. ```java public java.lang.String getServer() ```