访问匿名类的构造函数 [英] Accessing constructor of an anonymous class

查看:127
本文介绍了访问匿名类的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具体的类Class1,我正在创建一个匿名类。

Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.

Object a = new Class1(){
        void someNewMethod(){
        }
      };

现在有任何方法可以重载这个匿名类的构造函数。如下所示

Now is there any way I could overload the constructor of this anonymous class. Like shown below

Object a = new Class1(){
        void someNewMethod(){
        }
        public XXXXXXXX(int a){
          super();
          System.out.println(a);
        }
      };

用xxxxxxxx命名构造函数?

With something at xxxxxxxx to name the constructor?

推荐答案

Java语言规范,第15.9.5.1节:

From the Java Language Specification, section 15.9.5.1:


匿名类不能有
显式声明构造函数。

An anonymous class cannot have an explicitly declared constructor.

对不起:(

:作为一种替代方法,您可以创建一些最终局部变量,和/或在匿名类中包含一个实例初始化器。例如:

As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:

public class Test {
    public static void main(String[] args) throws Exception {
        final int fakeConstructorArg = 10;

        Object a = new Object() {
            {
                System.out.println("arg = " + fakeConstructorArg);
            }
        };
    }
}

这是grotty,但它可能只是帮助你。或者,使用适当的嵌套类:)

It's grotty, but it might just help you. Alternatively, use a proper nested class :)

这篇关于访问匿名类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆