#define ONE 2

Adam Hinz: The Blog

constructor invocation, what's your method

On 2007-07-13 at 7/13/2007 11:54:00 PM...

Snow Patrol - How to be Dead

I love it when I learn new things.

A couple weeks ago I discovered Java's Class, Method, and Constructor classes. I didn't have any use for them at the time, but I lodged them into the back right corner of my mind.

Tonight, I was trying to think of a better way to deal with the 'phantom' data for my layout manager. Basically, a phantom is a string assigned to a GUI object that tells it how wide to be. If a text field was to accept a phone number, you might give it a phantom of "555-555-5555", and the width of the field would be wide enough to hold exactly that many characters.

The code is enough. Grab the original text, set the text to the phantom, calculate the size, restore the original text. The problem is with Java's type system. Before calling getText or setText, you have to cast it. The original code (before I arrived) had a series of else-if statements for all the different types that we might want to use phantoms on. I originally did it this way for ease and laziness, but it always kind of bugged me.

Well, today I fixed it all up, and the result is pretty slick.

  1. try{

  2. Method getText = child.getClass().getDeclaredMethod("getText", new Class[]{});

  3. Method setText = child.getClass().getDeclaredMethod("setText", new Class[]{String.class});

  4. try{

  5. Object oldText = getText.invoke(child, new Object[]{});

  6. setText.invoke(child, new Object[]{boxData.phantom});

  7. size = child.computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);

  8. setText.invoke(child, new Object[]{oldText});

  9. }

  10. catch(InvocationTargetException ex){}

  11. catch(IllegalAccessException ex){}

  12. }

  13. catch(NoSuchMethodException ex){}

  14. catch(SecurityException ex){}



It still uses exceptions, which I try to avoid, but there's no way around it this time.

0 comments

Other places where I exist


Archive