java - Passing inline constructed class as a Class argument to a method -
i need call following method.
void foo(class<? extends bar> cls);
for cls
argument, need pass class overrides single method of bar
.
i want know whether there way write definition of new class inline in above call without writing new class in separate file extends bar.
three options:
you create nested class within same class want use code; no need new file
public static void dosomething() { foo(baz.class); } private static class baz extends bar { // override method }
you declare named class within method:
public static void dosomething() { class baz extends bar { // override method } foo(baz.class); }
declaring class within method highly unusual, mind you.
you use anonymous inner class, call
getclass()
:public static void dosomething() { foo(new bar() { // override method }.getclass()); }
the last option creates instance of anonymous inner class just class
object of course, isn't ideal.
personally i'd probably go first option.
Comments
Post a Comment