Java Pub House (general)

Episode 25. Reflection and vampire classes, and compiling Java from within Java.

We have heard the word "Reflection" thrown around, what does it mean? it is a new Twilight series? is it about Vampires? In all, we shed sunlight into what reflection is (and more importantly why in the world you want to use it). And also cover a technique to compile and load programs within your program. Javascript guys had access to this by doing eval("your program here"), and while Java doesn't have an eval function, there are ways of achieving similar results (and very specific reasons to do this crazy technique. Mostly performance)


It's SUMMER! If you like what you hear, DEFINITIVELY, treat me a beer ! :) (It's the Java pub house after all :)


Nimbus code to get the dang CacheMode (considered a private variable)

public class ButtonPainter extends AbstractRegionPainter {
    public ButtonPainter() {

        Class<?> c = null;
        PaintContext ctx = new PaintContext(new Insets(0,0,0,0), new Dimension(100,100), false, null, Double.POSITIVE_INFINITY, 2.0 );

        try {
            c = Class.forName("javax.swing.plaf.nimbus.AbstractRegionPainter$PaintContext$CacheMode");
        } catch (ClassNotFoundException e) {
        if (c != null) {
            Object cacheMode = c.getEnumConstants()[2];			// NINE_SQUARE_SCALE
            for (Field field : ctx.getClass().getDeclaredFields()) {
                if (c.getName().equals(field.getType().getName())) {        // if Field is the CacheMode
                    try {
                        // the following lines would not be necessary for example if
                        // AbstractRegionPainter.cacheMode were protected or public.

                        field.setAccessible(true);                          // make it accessible so that we can set it
                        field.set(ctx, cacheMode);                          // set the cachemode
                        // this is equivalent as sayin "ctx.cacheMode = CacheMode.NINE_SQUARE_SCALE" if it were public/protected
                    } catch (IllegalAccessException e) {


    protected PaintContext getPaintContext() {
        return null;  //To change body of implemented methods use File | Settings | File Templates.

    protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {
        //To change body of implemented methods use File | Settings | File Templates.

Code to get instance from a source file

    public static Object getInstanceForSource(String className, String sourceForRule) {
        String filename = "tmp/" + className + ".java";
        File file = new File(filename);
        writeFile(filename, sourceForRule);				
        String classPath = System.getProperty("java.class.path");
        String[] args = new String[]{
                "-classpath", classPath,

        StringWriter compilerOutput = new StringWriter();
        int status =,new PrintWriter(compilerOutput));
        additionalInfo.value = compilerOutput.toString();
        switch (status) {
            case 0:  // OK
                // Make the class file temporary as well
                File classFile = new File("./tmp/");
                try {
                    // Try to access the class and run its main method
                    URLClassLoader loader = new URLClassLoader(new URL[] {classFile.toURI().toURL()});
                    Class clazz = loader.loadClass(className);
                    return clazz.newInstance();
                } catch (Exception ex) {
                    additionalInfo.value = "Exception in main: " + Utilities.exceptionToString(ex)+"\n"+additionalInfo.value;
            case 1:
                System.out.println ("Status: Error" +"\n"+additionalInfo.value);
            case 2:
                System.out.println ("Status: CMDERR" +"\n"+additionalInfo.value);
            case 3:
                System.out.println ("Status: SYSERR" +"\n"+additionalInfo.value);
            case 4:
                System.out.println ("Status: ABNORMAL" +"\n"+additionalInfo.value);
                System.out.println ("Status: UNKNOWN" +"\n"+additionalInfo.value);
        return null;

    public static void writeFile(String fileName, String content) {
        Writer writer;
        File file = new File(fileName);
        try {
            writer = new BufferedWriter(new FileWriter(file));
        } catch (IOException e) {
           System.out.println ("I/O exception "+e);

Tweet, Tweet!(!/fguime)

Reflection 'trail'
Create dynamic applications with
URLClassLoaders (loads .class files generated

Vote for us in iTunes(

Questions, feedback or comments!

Subscribe to our podcast! (
ITunes link (
Java 7 Recipes book!(

Hey! if you like what you hear, treat me a beer! (It's the Java pub house after all :)

Direct download: JPHE25.mp3
Category:general -- posted at: 11:01pm CST

In this podcast we turn and talk of that embarassing uncle that every API has (, you know, the one that you have to live with because is family, but don't really like that much? We dive into what to avoid when using Date (and Calendar), and the most common pitfalls that we have falled for (1000*60*60*24 anyone?). In all, if you have used date extensively you probably already migrated to JodaTime, but if you are a casual user, then take a listen, just to make sure you are not bitten by the Date traps!

Vote for us in iTunes (
Follow us in Twitter!!/fguime (Joda Time) Date JSR + what goes under the covers)

Questions, feedback or comments!

Subscribe to our podcast! (
ITunes link (
Java 7 Recipes book! (

Direct download: JPHE20.mp3
Category:general -- posted at: 8:19pm CST

We finish our discussion on the ObjectOutputStream by covering the SerialVersionUID, and then move onto ObjectOutputStream's citadine cousin, XMLEncoder and Decoder (and why would you go and hang out with it). We also make a quick introduction to "The Bean" (Java Beans that is), and discover there isn't too much to it. If you are persisting and/or transmitting, listen to the shocking conclusion (gasp!) of serialization!

Rate us in  iTunes (
Follow us in Twitter!!/fguime (Serialization/Deserialization) (Compatible/Incompatible serialization changes)

Questions, feedback or comments!

Subscribe to our podcast! (
ITunes link (
Java 7 Recipes book! (

Direct download: JPHE19.mp3
Category:general -- posted at: 10:52pm CST

We all have the need to serialize/deserialize objects (either through the "wire" or to file). In this podcast we go and analyze what exactly happens when we create an ObjectOutputStream and write to it, and more importantly what pitfalls are there to avoid (Out ot memory errors, stale object updates, Not Serializable Exceptions, and toenail fungus!). If you ever considered using ObjectOutput/InputStream, or are actively using in your current projects, take a listen! (Serialization performance comparison for Java, pick one!)

Questions, feedback or comments!

Subscribe to our podcast! (
ITunes link (
Java 7 Recipes book! (

Direct download: JPHE18.mp3
Category:general -- posted at: 8:04pm CST

In this episode we go over Aspects (and AspectJ), what really is, and when to use them. It turns out, that there is nothing misterious about them! We also cover how to set-up Aspects for J2SE so you can start using them immediately!

Questions, feedback or comments!

VM Parameter

Example Aspect


public class OrderAspect {

@Before("execution(* *.*(Order))") // must qualify
public void anyCall() {
System.out.println("Was called from anywhere");

Example aop.xml file

<aspect name="OrderAspect"/>
<weaver options="-verbose -showWeaveInfo">

Example Folder Structure



(Using aspects with annotations)

Direct download: JPHE8.mp3
Category:general -- posted at: 3:00pm CST

In this episode of Java pub house, we talk about Deadlocks, livelocks (and other spooky things). Most importantly we talk on how to spot them (using jstack, or visualvm), and how to program defensively against them. We also talk about escaped locks (the source of most deadlocks), and the wait/notify language construct. Finally we describe the unfairness of the lock (locks are not "fair" by default), and why is it so.

Direct download: JPHE2.mp3
Category:general -- posted at: 12:04pm CST