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!

PunkPengu
  • 32
  • 1

1 Answers1

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";
    }
}
vbezhenar
  • 11,148
  • 9
  • 49
  • 63