Q: Elegant way to repace the (Class-)Type of an Instance in Java bytecode I've been working for some time on a solution for the following problem. Let's say I have following Java code:
public class A {
  public void start() {
    List l = new ArrayList();
    l.add("abc");
    System.out.println( l.get(0) );
  }
}

The result of compiling this code is a class file A.class, containing Java byte code. I've written a ClassLoader, which loads A.class and executes start(). My intention is replacing in the loaded A.class (byte code) new ArrayList() with MyArrayList():
//Before
List l = new ArrayList();
//After
List l = new MyArrayList();

The class MyArrayList is defined similarly to: class MyArrayList extends ArrayList

A: You can use a tool like ASM to parse the file and to replace the occurrence of any ArrayList with MyArrayList. This would however require that MyArrayList defines constructors with an identical signature to the constructors defined in ArraysList.
The next question is when you define the changes. You have the following possibilities:


*

*Change the implementation at build time: You could write a build tool plugin that applies your transformations.

*Change the implementation at run time using a Java agent: The Attach API allows you to change a loaded class even at run time.

*Change the implementation before a class is loaded for a first time: You could use a custom class loader for loading your altered class. This needs to happen before a class is loaded regularly!

