Passing an inline constructed class as a class argument to a method
I need to call the following method.
void foo(Class<? extends Bar> cls);
For the argument, cls
I need to pass a class that only overrides one method Bar
.
I want to know if there is a way to write the definition of my new inline class in the above call without writing the new class in a separate file that extends Bar.
source to share
Three options:
-
You can create a nested class in the same class where 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 can declare a named class in a method:
public static void doSomething() { class Baz extends Bar { // Override a method } foo(Baz.class); }
Declaring a class inside a method like this is very unusual, mind you.
-
You can 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 an anonymous inner class just to get an object Class
, of course, which is not perfect.
Personally, I would choose the first option.
source to share