Instantiating an inner class

前端 未结 4 1474
逝去的感伤
逝去的感伤 2020-12-29 08:51

I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this:

public static  List<         


        
4条回答
  •  被撕碎了的回忆
    2020-12-29 09:45

    Something more generic:

        public static  T createInstance(final Class clazz) throws SecurityException, NoSuchMethodException,
                IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
    
                T instanceToReturn = null;
                Class< ? > enclosingClass = clazz.getEnclosingClass();
    
                if (enclosingClass != null) {
                    Object instanceOfEnclosingClass = createInstance(enclosingClass);
    
                    Constructor ctor = clazz.getConstructor(enclosingClass);
    
                    if (ctor != null) {
                        instanceToReturn = ctor.newInstance(instanceOfEnclosingClass);
                    }
                } else {
                    instanceToReturn = clazz.newInstance();
                }
    
                return instanceToReturn;
         }
    

提交回复
热议问题