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

Published: June 7, 2012, 4:01 a.m.

b'

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

\\n

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)

\\n

\\xa0

\\n

It\'s SUMMER! If you like what you hear, DEFINITIVELY, treat me a beer ! :) (It\'s the Java pub house after all :) https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Z8V2ZWV93UMW4

\\n

\\xa0

\\n

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

\\n
\\npublic class ButtonPainter extends AbstractRegionPainter {\\n    public ButtonPainter() {\\n\\n        Class c = null;\\n        PaintContext ctx = new PaintContext(new Insets(0,0,0,0), new Dimension(100,100), false, null, Double.POSITIVE_INFINITY, 2.0 );\\n\\n        try {\\n            c = Class.forName("javax.swing.plaf.nimbus.AbstractRegionPainter$PaintContext$CacheMode");\\n        } catch (ClassNotFoundException e) {\\n            e.printStackTrace();\\n        }\\n        if (c != null) {\\n            Object cacheMode = c.getEnumConstants()[2];\\t\\t\\t// NINE_SQUARE_SCALE\\n            for (Field field : ctx.getClass().getDeclaredFields()) {\\n                if (c.getName().equals(field.getType().getName())) {        // if Field is the CacheMode\\n                    try {\\n                        // the following lines would not be necessary for example if\\n                        // AbstractRegionPainter.cacheMode were protected or public.\\n\\n                        field.setAccessible(true);                          // make it accessible so that we can set it\\n                        field.set(ctx, cacheMode);                          // set the cachemode\\n                        // this is equivalent as sayin "ctx.cacheMode = CacheMode.NINE_SQUARE_SCALE" if it were public/protected\\n                        break;\\n                    } catch (IllegalAccessException e) {\\n                        e.printStackTrace();\\n                    }\\n                }\\n            }\\n        }\\n\\n    }\\n\\n    @Override\\n    protected PaintContext getPaintContext() {\\n        return null;  //To change body of implemented methods use File | Settings | File Templates.\\n    }\\n\\n    @Override\\n    protected void doPaint(Graphics2D g, JComponent c, int width, int height, Object[] extendedCacheKeys) {\\n        //To change body of implemented methods use File | Settings | File Templates.\\n    }\\n}\\n\\n\\n\\n\\n\\n
\\n

Code to get instance from a source file

\\n
    public static Object getInstanceForSource(String className, String sourceForRule) {\\n        String filename = "tmp/" + className + ".java";\\n        File file = new File(filename);\\n        writeFile(filename, sourceForRule);\\t\\t\\t\\t\\n        String classPath = System.getProperty("java.class.path");\\n        String[] args = new String[]{\\n                "-classpath", classPath,\\n                filename\\n        };\\n\\n\\n        StringWriter compilerOutput = new StringWriter();\\n        int status = com.sun.tools.javac.Main.compile(args,new PrintWriter(compilerOutput));\\n        additionalInfo.value = compilerOutput.toString();\\n        switch (status) {\\n            case 0:  // OK\\n                // Make the class file temporary as well\\n                File classFile = new File("./tmp/");\\n                try {\\n                    // Try to access the class and run its main method\\n                    URLClassLoader loader = new URLClassLoader(new URL[] {classFile.toURI().toURL()});\\n                    Class clazz = loader.loadClass(className);\\n                    return clazz.newInstance();\\n                } catch (Exception ex) {\\n                    additionalInfo.value = "Exception in main: " + Utilities.exceptionToString(ex)+"\\\\n"+additionalInfo.value;\\n                }\\n                break;\\n            case 1:\\n                System.out.println ("Status: Error" +"\\\\n"+additionalInfo.value);\\n                break;\\n            case 2:\\n                System.out.println ("Status: CMDERR" +"\\\\n"+additionalInfo.value);\\n                break;\\n            case 3:\\n                System.out.println ("Status: SYSERR" +"\\\\n"+additionalInfo.value);\\n                break;\\n            case 4:\\n                System.out.println ("Status: ABNORMAL" +"\\\\n"+additionalInfo.value);\\n                break;\\n            default:\\n                System.out.println ("Status: UNKNOWN" +"\\\\n"+additionalInfo.value);\\n                break;\\n        }\\n        return null;\\n    }\\n\\n    public static void writeFile(String fileName, String content) {\\n        Writer writer;\\n        File file = new File(fileName);\\n        try {\\n            writer = new BufferedWriter(new FileWriter(file));\\n            writer.write(content);\\n            writer.close();\\n        } catch (IOException e) {\\n           System.out.println ("I/O exception "+e);\\n        }\\n    }\\n\\n\\n
\\n

Tweet, Tweet!(https://twitter.com/#!/fguime)

\\n

Reflection \'trail\' http://docs.oracle.com/javase/tutorial/reflect/index.html
Create dynamic applications with javax.tools http://www.ibm.com/developerworks/java/library/j-jcomp/index.html
URLClassLoaders (loads .class files generatedhttp://docs.oracle.com/javase/6/docs/api/java/net/URLClassLoader.html

\\n

Vote for us in iTunes(http://itunes.apple.com/us/podcast/java-pub-house/id467641329)

\\n

Questions, feedback or comments! comments@javapubhouse.com

\\n

Subscribe to our podcast! (http://javapubhouse.libsyn.com/rss)
ITunes link (http://itunes.apple.com/us/podcast/java-pub-house/id467641329)
Java 7 Recipes book!(http://www.amazon.com/gp/product/1430240563/ref=as_li_ss_il?ie=UTF8&tag=meq-20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1430240563)

\\n

Hey! if you like what you hear, treat me a beer! (It\'s the Java pub house after all :) https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Z8V2ZWV93UMW4

'