Java – pass the inline constructed class to the method as a class parameter
I need to call the following method
void foo(Class<? extends Bar> cls);
For the CLS parameter, I need to pass a class that only overrides a single method of bar
I wonder if there is a way to write the inline definition of my new class in the above call itself without writing the new class in a separate file extending the bar
Solution
Three options:
>You can create nested classes in the same class that you want to use this code; No new files are required
public static void doSomething() { foo(Baz.class); } private static class Baz extends Bar { // Override a method }
>You can declare a named class in a method:
public static void doSomething() { class Baz extends Bar { // Override a method } foo(Baz.class); }
It is very unusual to declare a class in such a method. Please note. > You can use anonymous internal classes, but then call getClass ():
public static void doSomething() { foo(new Bar() { // Override a method }.getClass()); }
The last option creates an instance of an anonymous inner class just to get the class object, which is certainly not ideal
Personally, I may choose the first option