Accessing constructor of an anonymous class

后端 未结 10 2059
借酒劲吻你
借酒劲吻你 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:31

    Peter Norvig's The Java IAQ: Infrequently Answered Questions

    http://norvig.com/java-iaq.html#constructors - Anonymous class contructors

    http://norvig.com/java-iaq.html#init - Construtors and initialization

    Summing, you can construct something like this..

    public class ResultsBuilder {
        Set<Result> errors;
        Set<Result> warnings;
    
    ...
    
        public Results<E> build() {
            return new Results<E>() {
                private Result[] errorsView;
                private Result[] warningsView;
                {
                    errorsView = ResultsBuilder.this.getErrors();
                    warningsView = ResultsBuilder.this.getWarnings();
                }
    
                public Result[] getErrors() {
                    return errorsView;
                }
    
                public Result[] getWarnings() {
                    return warningsView;
                }
            };
        }
    
        public Result[] getErrors() {
            return !isEmpty(this.errors) ? errors.toArray(new Result[0]) : null;
        }
    
        public Result[] getWarnings() {
            return !isEmpty(this.warnings) ? warnings.toArray(new Result[0]) : null;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 03:33

    In my case, a local class (with custom constructor) worked as an anonymous class:

    Object a = getClass1(x);
    
    public Class1 getClass1(int x) {
      class Class2 implements Class1 {
        void someNewMethod(){
        }
        public Class2(int a){
          super();
          System.out.println(a);
        }
      }
      Class1 c = new Class2(x);
      return c;
    }
    
    0 讨论(0)
  • 2020-11-28 03:35

    That is not possible, but you can add an anonymous initializer like this:

    final int anInt = ...;
    Object a = new Class1()
    {
      {
        System.out.println(anInt);
      }
    
      void someNewMethod() {
      }
    };
    

    Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

    0 讨论(0)
  • 2020-11-28 03:35

    It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.

    Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.

    0 讨论(0)
  • 2020-11-28 03:43

    If you dont need to pass arguments, then initializer code is enough, but if you need to pass arguments from a contrcutor there is a way to solve most of the cases:

    Boolean var= new anonymousClass(){
        private String myVar; //String for example
    
        @Overriden public Boolean method(int i){
              //use myVar and i
        }
        public String setVar(String var){myVar=var; return this;} //Returns self instane
    }.setVar("Hello").method(3);
    
    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题