Accessing constructor of an anonymous class

后端 未结 10 2083
借酒劲吻你
借酒劲吻你 2020-11-28 03:17

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

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


        
10条回答
  •  时光取名叫无心
    2020-11-28 03:47

    From the Java Language Specification, section 15.9.5.1:

    An anonymous class cannot have an explicitly declared constructor.

    Sorry :(

    EDIT: 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);
                }
            };
        }
    }
    

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

提交回复
热议问题