Delude java about generic with two step compilation

After “Generics inside byte code ?” we can be curious about the behavior of byte code at runtime.

After compilation generics disappear, and javac is aware of the real generic type, but can I delude java at runtime ?
Try to perform this tasks :
1/ Compile two classes. One of these use List<String>

public class L {
    public void doSomething(List<String> l) {
        l.add("str");
    }
}
public class M {
    public static void main(String[] argv) {
    new L().doSomething(new ArrayList<String>());
    }
}

2/ Recompile just the class which uses List<String> and modify it to use <Integer>

public class L {
    public void doSomething(List<Integer> l) {
        l.add(42);
    }
}

3/ Replace the old .class version

You can now run your application which calls doSomething(List<Integer> l) from doSomething(new ArrayList<String>()).

It’s not a good practice, it’s juste a trick which allows a better understanding of java 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s