将内联构造的类作为Class参数传递给方法

3
我需要调用以下方法。
void foo(Class<? extends Bar> cls);

对于cls参数,我需要传递一个仅覆盖Bar单个方法的类。

我想知道是否有一种方式可以在以上调用中内联编写新类的定义,而无需编写一个独立文件中继承Bar的新类。

2个回答

5

三个选项:

  • 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());
    }
    
最后一个选项创建了一个匿名内部类的实例,只是为了获得当然的 Class 对象,这并不理想。
个人而言,我会可能选择第一个选项。

在上述三个选项中,只有第一个选项允许foo通过cls.newInstance()创建一个新实例。 - Lahiru Chandima
@LahiruChandima:即使doSomething是一个静态方法?有趣而令人惊讶 - 我怀疑编译器在没有捕获变量的情况下也会添加构造函数参数。 - Jon Skeet
我没有使用静态的 doSomething() 进行检查。在我的情况下,我需要在非静态上下文中调用 foo - Lahiru Chandima

2

是的,您可以声明一个匿名类并使用 getClass() 方法:

foo(new Bar() {
    //implement your method here
}.getClass());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接