There is a class in which the designer is required to transfer the interface. How to get its copy if there is a class that implements this interface and I can create an instance of such a class.

PS Reflection

  • I know about the usability of Reflection API) I do not understand how to get the interface instance - Flippy
  • Whether it is possible to use not an interface but a class of its inheritance? - Flippy
  • как получить инстанс интерфейса - no way. But the task is not very clear. Try adding sample code. - post_zeew
  • So create: Animal animal = new Dog(); . Animal - the interface, Dog - the class that implements it. What is reflection needed for? - Regent

1 answer 1

Creating an object through reflection is more expensive than a simple constructor call, so if you can, try to avoid reflection.

As for the question itself, do I understand correctly that you need to create an object through a constructor, whose argument is the interface?

 public class Person { private final int size; public Person(List list) { size = list != null ? list.size() : 0; } public int getSize() { return size; } } 

In this case, simply take the desired constructor, substitute the implementation as an argument, and create an object.

 public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class clazz = Person.class; Constructor constructor = clazz.getConstructor(List.class); Person person = (Person) constructor.newInstance(Arrays.asList(1, 2, 3)); System.out.println(person.getSize()); }