Java Challenge – The Mysterious Method Wrapper

Here is the challenge. Create some Java code so that this JUnit test works:

public class EachMethodTest {

    /**
     * Simple test object.
     */
    public static class Fu {
        @Callable
        public int fu() {
            return 1;
        }

        @Callable
        public int bar() {
            return 2;
        }
    }

    /**
     * Call all methods that have the @Callable annotation.
     * The MethodsToProc works for ANY type of object, not just Fu.
     */
    @Test
    public void eachMethodTest() {
        final Fu fu = new Fu();

        int sum = 0;
        for (final Proc<integer> c : new MethodsToProc<integer>(fu)) {
            sum += c.call();
        }

        Assert.assertEquals(3, sum);
    }
}

Basically what I want to do is be able to automatically create wrappers for some object, so that each method with the @Callable can be called with a single common wrapper interface call(). It should be possible to specify the return type via Generics, and the ctor of MethodsToProc should be able to take any type of object.

See if you can do a general solution without cheating! The simpler, the better. You can post code snippets e.g. at snipit or gist. Have fun!

Related posts

  1. Amazing Caching Proxy in Java
  2. Optimized Exponential Functions for Java
  3. Ruby Programming Challenge
  4. Optimized pow() approximation for Java, C / C++, and C#
  5. Approximation of sqrt(x) in Java

4 thoughts on “Java Challenge – The Mysterious Method Wrapper

  1. I wasn’t so sure about the purpose of having each callable be wrapped in a Proc — seemed like just using the returns values was much simpler (two classes less ;) but providing the same abilities.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>