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?

Anand
  • 20,708
  • 48
  • 131
  • 198
  • Yes there is. For an example, see http://stackoverflow.com/questions/3925587/java-reflection-calling-constructor-with-primitive-types – NPE May 19 '12 at 10:27

2 Answers2

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");
raphaëλ
  • 6,393
  • 2
  • 29
  • 35
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");
kapex
  • 28,903
  • 6
  • 107
  • 121