Passing inline constructed class as a Class argument to a method

I need to call following method.

void foo(Class<? extends Bar> cls);

For cls argument, I need to pass a class that only overrides a single method of Bar.

I want to know whether there is a way to write the definition of my new class inline in above call itself without writing a new class in a separate file which extends Bar.

Jon Skeet
people
quotationmark

Three options:

  • You could create a nested class within the same class you want to use this code; no need for a new file

    public static void doSomething() {
        foo(Baz.class);
    }
    
    private static class Baz extends Bar {
        // Override a method
    }
    
  • You could declare a named class within the method:

    public static void doSomething() {
        class Baz extends Bar {
            // Override a method
        }
        foo(Baz.class);
    }
    

    Declaring a class within a method like this is highly unusual, mind you.

  • You could use an anonymous inner class, but then call getClass():

    public static void doSomething() {
        foo(new Bar() {
            // Override a method
        }.getClass());
    }
    

The last option creates an instance of the anonymous inner class just to get the Class object of course, which isn't ideal.

Personally I'd probably go for the first option.

people

See more on this question at Stackoverflow