0

We can use reflection to create the objects. Let's say I have a class "Employee" in package p

Employee emp = Employee.class.newInstance()  OR
Employee emp = (Employee)Class.forName("p.Employee").newInstance() 

Above lines of code will create Employee object by calling Employee's default or no-arg constructor. And then I set some values to objects by calling setters of Employee

Is there any way of creating objects using reflection by giving values in the constructor itself i.e. by calling parameterized constructor?

1

2 Answers 2

2

Yes, let's assume Foo has a constructor that accepts an Single String as its argument. Then using the following code gives an instance using that constructor:

Class<?> fooClass = Foo.class;
Constructor<?> constructor = fooClass.getConstructor(String.class);
Object obj = constructor.newInstance("hello");
Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at Class.getConstructor and Constructor.

First you get the right constructor by its parameter types, then you call it with arguments of that type:

Constructor<Employee> constructor = Class.forName("p.Employee").getConstructor(Integer.class, String.class);
Employee employee = constructor.newInstance(1,"foo");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.