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
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
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()); } Source: https://ru.stackoverflow.com/questions/622684/
All Articles
как получить инстанс интерфейса- no way. But the task is not very clear. Try adding sample code. - post_zeewAnimal animal = new Dog();.Animal- the interface,Dog- the class that implements it. What is reflection needed for? - Regent