Call a method after the constructor has ended

前端 未结 7 784
迷失自我
迷失自我 2020-12-31 07:19

I need to call a method after the constructor has ended and I have no idea how to do. I have this class:

Class A {
    public A() {
        //...
    }

             


        
7条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 07:52

    I pick up some ideas and provide an abstractable solution:

    class A {
        protected A() {
            // ...
        }
        protected void init() {
            // ...
        }
        public static  T create(Class type) {
            try {
                T obj = type.newInstance();
                obj.init();
                return obj;
            } catch (ReflectiveOperationException ex) {
                System.err.println("No default constructor available.");
                assert false;
                return null;
            }
        }
    }
    

提交回复
热议问题