Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Get a load of that name!

Subtle differences in various ways you can dynamically load a class

  • Print
  • Feedback

Page 3 of 3

public class Main
{
    public static void main (String [] args) throws Exception
    {
        System.out.println ("String class: " + String.class);
        class$java$lang$String = int.class;
        System.out.println ("String class: " + String.class);
    }
    
    static Class class$java$lang$String;
} // End of class


If you run it, you will get the following, which is ridiculous at best:

>java Main
String class: class java.lang.String
String class: int


At least the compiler in J2SE 1.4.1 will reject the code above. But you can still fool it by setting the field reflectively:

    public static void main (String [] args) throws Exception
    {
        System.out.println ("String class: " + String.class);
        Main.class.getDeclaredField ("class$java$lang$String").set (null, int.class);
        System.out.println ("String class: " + String.class);
    }


So, next time you code the familiar Class.forName() incantation, you should know what it entails and what alternatives exist.

About the author

Vladimir Roubtsov has programmed in a variety of languages for more than 13 years, including Java since 1995. Currently, he develops enterprise software as a senior developer for Trilogy in Austin, Texas.
  • Print
  • Feedback

Resources