0

I need to write a functional interface call for a new instance of a dynamic object.

Classic way if I would know the class:

() -> new DefinedClass()

But I don't know the exact class. I only have the Class Object of the Class I try to instantiate.

Thx for help!

9
  • You can use the built-in Supplier<DefinedClass>
    – ernest_k
    Feb 27, 2020 at 9:17
  • 1
    Do you mean? Class clazz = ...; Object obj = clazz.newInstance()?
    – Eran
    Feb 27, 2020 at 9:18
  • newInstance() doesn't work in this functional context.
    – PunkPengu
    Feb 27, 2020 at 9:22
  • Does this answer your question? instantiate class from class object
    – Torben
    Feb 27, 2020 at 9:23
  • And why wouldn't newInstance() work? You're kinda supposed to explain yourself without being asked
    – kumesana
    Feb 27, 2020 at 9:27

1 Answer 1

2
package test;

import java.util.stream.Stream;

public class Test {
    public static void main(String[] args) {
        Stream.of(Test.class)
                .map(c -> {
                    try {
                        return c.newInstance();
                    } catch (IllegalAccessException | InstantiationException e) {
                        throw new RuntimeException(e);
                    }
                })
                .forEach(System.out::println);
    }

    @Override
    public String toString() {
        return "Test";
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.