Java 8 Supplier with arguments in the constructor

后端 未结 8 1954
小蘑菇
小蘑菇 2020-12-01 00:07

Why do suppliers only support no-arg constructors?

If the default constructor is present, I can do this:

create(Foo::new)

But if th

8条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 00:18

    If you have a constructor for new Klass(ConstructorObject) then you can use Function like this:

    interface Interface {
        static Klass createKlass(Function, Klass> func, Map input) {
            return func.apply(input);
        }
    }
    class Klass {
        private Integer integer;
        Klass(Map map) {
            this.integer = map.get("integer");
        }
        public static void main(String[] args) {
            Map input = new HashMap<>();
            input.put("integer", 1);
            Klass klazz = Interface.createKlass(Klass::new, input);
            System.out.println(klazz.integer);
        }
    }
    

提交回复
热议问题